Pyramid 是一个 Python Web 应用框架,它提供了构建现代 Web 应用的工具和组件。本教程将帮助你入门 Pyramid 框架。

快速开始

  1. 安装 Pyramid 使用 pip 安装 Pyramid:

    pip install pyramid
    
  2. 创建基础应用 创建一个名为 myapp 的目录,并在其中创建一个名为 config.py 的文件,内容如下:

    from pyramid.config import Config
    config = Config()
    
    @config.add_route('home', '/')
    @config.add_view('myapp.views.home', route_name='home')
    class Home:
        def __init__(self, request):
            self.request = request
    
        def __call__(self):
            return 'Hello, World!'
    

    接着,创建一个名为 views.py 的文件,内容如下:

    from pyramid.view import view
    from pyramid.response import Response
    
    @view()
    def home(request):
        return Response('Hello, World!')
    
  3. 运行应用 在终端中运行以下命令来启动应用:

    pyramid serve
    

    打开浏览器并访问 http://localhost:6543/,你应该会看到 "Hello, World!" 的输出。

路由和视图

Pyramid 使用路由和视图来处理 Web 请求。路由定义了 URL 与视图之间的映射关系。

定义路由

config.py 文件中,你可以使用 @config.add_route 装饰器来定义路由:

from pyramid.config import Config

config = Config()

@config.add_route('home', '/')
@config.add_view('myapp.views.home', route_name='home')
class Home:
    # ...

在上面的示例中,我们定义了一个名为 home 的路由,它将 / 路径映射到 Home 视图。

定义视图

视图是处理 Web 请求的函数或类。在上面的示例中,我们定义了一个名为 home 的视图,它返回 "Hello, World!"。

进一步学习

要了解更多关于 Pyramid 的信息,请访问Pyramid 官方文档

回到首页