Python Pyramid 简明教程

Python Pyramid - Application Configuration

Pyramid 应用程序对象拥有一个应用程序注册表,用于存储视图函数到路由的映射,以及其他特定于应用程序的组件注册。Configurator 类用于构建应用程序注册表。

The Pyramid application object has an application registry that stores mappings of view functions to routes, and other application-specific component registrations. The Configurator class is used to build the application registry.

Configurator 生命周期由上下文管理器管理,它返回一个应用程序对象。

The Configurator life cycle is managed by a context manager that returns an application object.

with Configurator(settings=settings) as config:
   #configuration methods
   app = config.make_wsgi_app()

Configurator 类定义了下列重要方法,用于自定义应用程序 −

The Configurator class defines the following important methods to customize the application −

add_route()

此方法注册一个路由用于 URL 派发。使用以下参数 −

This method registers a route for URL dispatch. Following arguments are used −

  1. name − The first required positional argument must be a unique name for the route. The name is used to identify the route when registering views or generating URLs.

  2. pattern − The second required positional argument is a string representing the URL path optionally containing variable placeholders for parsing the variable data from the URL. The placeholders are surrounded by curly brackets. For example, "/students/{id}".

  3. request_method − The value can be one of "GET", "POST", "HEAD", "DELETE", "PUT". Requests only of this type will be matched against the route.

add_view()

此方法会向应用程序注册表添加视图配置。它将一个视图函数绑定到配置中的 route_name 。需要的参数有:

This method adds a view configuration to the application registry. It binds a view function to the route_name present in the configuration. The arguments required are −

  1. view − The name of a view function.

  2. route_name − A string that must match the name of a route configuration declaration.

  3. request_method − Either a string (such as "GET", "POST", "PUT", "DELETE", "HEAD" or "OPTIONS") representing an HTTP REQUEST_METHOD, or a tuple containing one or more of these strings.

add_static_view()

此方法会添加一个 view 用于呈现静态资产(如图片和 CSS 文件),并使用以下参数:

This method adds a view used to render static assets such as images and CSS files, and uses the following arguments −

  1. name − This argument is a string representing an application-relative local URL prefix, or a full URL.

  2. Path − This argument represents the path on disk where the static files reside. Its value can be an absolute or a package-relative path.

此方法进而调用 Configurator 对象的 add_route() 方法。

This method in turn calls the add_route() method of Configurator object.

add_notfound_view()

该方法添加一个视图,当视图查找程序在当前请求中找不到匹配的视图时执行。以下代码显示了一个示例:

This method adds a view to be executed when a matching view cannot be found for the current request. The following code shows an example −

from pyramid.config import Configurator
from pyramid.response import Response

def notfound(request):
   return Response('Not Found', status='404 Not Found')

config.add_notfound_view(notfound)

add_forbidden_view()

配置应用程序注册表,以定义在出现 HTTPForbidden 异常时执行的视图。参数列表包含对返回 403 状态响应的函数的引用。如果没有提供参数,则注册表会添加 default_exceptionresponse_view().

Configures the application registry so as to define a view to be executed when there is HTTPForbidden exception raised. The argument list contains a reference to a function that returns a 403 status response. If no argument is provided, the registry adds default_exceptionresponse_view().

add_exception_view()

此方法导致为指定异常向配置中添加异常视图函数。

This method causes addition of an exception view function to the configuration, for the specified exception.

make_wsgi_app()

此方法返回 Pyramid WSGI 应用程序对象。

This method returns a Pyramid WSGI application object.

scan()

此包装器用于注册视图。它导入所有应用程序模块,寻找 @view_config 装饰器。

This is a wrapper for registering views. It imports all application modules looking for @view_config decorators.

对于每个装饰器,它使用相同的关键字参数调用 config.add_view(view)。调用 scan() 函数会扫描包和所有子包中的所有装饰。

For each one, it calls config.add_view(view) with the same keyword arguments. A call to scan() function performs the scan of the package and all the subpackages for all the decorations.

执行应用程序注册表配置的一系列典型语句如下代码段所示:

A typical sequence of statements that performs configuration of application registry is as in the following code snippet −

from pyramid.config import Configurator

with Configurator() as config:
   config.add_route('hello', '/')
   config.add_view(hello_world, route_name='hello')
   app = config.make_wsgi_app()

这种应用程序配置方法被称为命令式配置。Pyramid 提供了另一种配置方法,称为装饰配置。

This approach towards configuration of the application is called imperative configuration. Pyramid provides another approach towards configuration, called as decorative configuration.

Declarative Configuration

有时,通过命令式代码进行配置变得非常困难,尤其在应用代码分散在许多文件中时。声明式配置是一种便捷的方法。 pyramid.view 模型定义了 view_config - 一个函数、类或方法修饰器,该修饰器允许在非常接近视图函数自身定义的位置注册视图。

Sometimes, it becomes difficult to do the configuration by imperative code, especially when the application code is spread across many files. The declarative configuration is a convenient approach. The pyramid.view model defines view_config – a function, class or method decorator - that allows the view registrations very close to the definition of view function itself.

@view_config() 修饰器提供了两个重要参数。它们是 route_namerequest_method 。它们与 Configurator 类的 add_route() 方法中给出的说明相同。紧跟在它下面的函数获得了修饰,以便将它绑定到添加到应用对象的注册表中的路由。

Two important arguments are provided to @view_config() decorator. They are route_name and request_method. They bear same explanation as in add_route() method of Configurator class. The function just below it is decorated so that it is bound to the route added to the registry of the application object.

以下是 hello_world() 视图函数声明式配置示例:

Give below is the example of declarative configuration of hello_world() view function −

from pyramid.response import Response
from pyramid.view import view_config

@view_config(route_name='hello', request_method='GET')
def hello_world(request):
   return Response('Hello World!')

view_config 修饰器向 hello_world() 函数添加了一个属性,使其可供扫描在之后找到它。

The view_config decorator adds an attribute to the hello_world() function, making it available for a scan to find it later.

Example

配置修饰和扫描调用共同称为声明式配置。以下代码使用声明式方法配置应用注册表。

The combination of configuration decoration and the invocation of a scan is collectively known as declarative configuration. Following code configures the application registry with declarative approach.

scan() 函数发现路由及其映射的视图,因此需要添加命令式配置语句。

The scan() function discovers the routes and their mapped views, so that there is the need to add imperative configuration statements.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

@view_config(route_name='hello', request_method='GET')
def hello_world(request):
   return Response('Hello World!')

if __name__ == '__main__':
   with Configurator() as config:
      config.add_route('hello', '/')
      config.scan()
      app = config.make_wsgi_app()
   server = make_server('0.0.0.0', 6543, app)
   server.serve_forever()

扫描器将 view_config 的参数翻译为对 pyramid.config.Configurator.add_view() 方法的调用,因此,该操作等同于以下语句:

The scanner translates the arguments to view_config into a call to the pyramid.config.Configurator.add_view() method, so that the action is equivalent to the following statement −

config.add_view(hello_world, route_name='hello', request_method='GET')

Output

运行上述程序之后,WSGI 服务器启动。当浏览器访问链接 [role="bare"] [role="bare"]http://localhost:6543/ 时,依然会渲染“Hello World”信息。

After the above program is run, the WSGI server starts. When the browser visits the link [role="bare"]http://localhost:6543/, the "Hello World" message is rendered as before.

config