The Main Function

Pyramid 和 Pylons 都有一个顶级函数,返回一个wsgi应用程序。 Pyramid 函数是 main 在里面 pyramidapp/__init__.py. The Pylons function is make_app 在里面 pylonsapp/config/middleware.py. Here's the main function generated by Pyramid's 'starter' scaffold:

 1from pyramid.config import Configurator
 2
 3def main(global_config, **settings):
 4    """ This function returns a Pyramid WSGI application.
 5    """
 6    config = Configurator(settings=settings)
 7    config.add_static_view('static', 'static', cache_max_age=3600)
 8    config.add_route('home', '/')
 9    config.scan()
10    return config.make_wsgi_app()

Pyramid 的样板代码比 Pylons 少,因此主要功能包括 Pylons 的middleware.py、environment.py和 and routing.py modules. Pyramid's configuration code is just 5 lines long in the default application, while Pylons' is 35.

Most of the function's body deals with the Configurator ( config )这不是应用程序对象;它是一个将为我们实例化应用程序的助手。将设置作为dict传递给构造函数(第6行),调用各种方法来设置路由等,最后调用 config.make_wsgi_app() 获取主函数返回的应用程序。应用程序是 pyramid.router.Router . ( Pylons 应用程序是 PylonsApp 子类)

Dotted Python names and asset specifications

Several config methods accept either an object (e.g., a module or callable) or a string naming the object. The latter is called a dotted Python name. It's a dot-delimited string specifying the absolute name of a module or a top-level object in a module: "module", "package.module", "package.subpackage.module.attribute". Passing string names allows you to avoid importing the object merely to pass it to a method.

如果字符串以前导点开头,则它与某个父包相关。所以在这 main function defined in mypyramiapp/__init__.py, the parent package is mypyramidapp . So the name ".views" refers to mypyramidapp/views.py. (注意:在某些情况下,有时很难猜测 Pyramid 认为父包是什么。)

Closely associated with this is a Static Assets规格,

存在另一种语法,在模块和属性之间使用冒号:“package.module:attribute”。不鼓励这种用法;它的存在是为了与SETUPTOOLS的资源语法兼容。

Configurator methods

The Configurator has several methods to customize the application. Below are the ones most commonly used in Pylons-like applications, in order by how widely they're used. The full list of methods is in Pyramid's Configurator API .

add_route(...)

Register a route for URL dispatch.

add_view(...)

注册视图。视图相当于 Pylons 的控制器动作。

scan(...)

用于注册视图和某些其他内容的包装器。在“视图”一章中讨论。

add_static_view(...)

添加发布静态文件目录的特殊视图。这有点类似于幽门的公共目录,但请参阅静态恶魔一章中的警告。

include(callable, route_prefix=None)

允许函数进一步自定义配置。这是一个广泛开放的界面,在Pyramid中非常流行。它有三个主要的用例:

  • 将相关代码分组在一起;例如,在单独的模块中定义路由。

  • 初始化第三方加载项。许多附加组件提供了一个include函数,它为您执行所有初始化步骤。

  • 在URL前缀处装入子应用程序。子应用程序只是一起工作的任何路由、视图和模板束。您可以使用它将应用程序拆分为逻辑单元。或者,您可以编写可在多个应用程序中使用的通用子应用程序,或者安装第三方子应用程序。

如果附加组件或子应用程序具有选项,则通常会从设置中读取它们,查找具有特定前缀的设置,并将字符串转换为正确的类型。例如,会话管理器可以查找以“session.”或“session manager.”开头的键,如“session.type”。请查阅附加组件的文档,了解它使用的前缀和识别的选项。

这个 callable argument should be a function, a module, or a dotted Python name. If it resolves to a module, the module should contain an includeme function which will be called. The following are equivalent:

1config.include("pyramid_beaker")
2
3import pyramid_beaker
4config.include(pyramid_beaker)
5
6import pyramid_beaker
7config.include(pyramid_beaker.includeme)

如果 route_prefix is specified, it should be a string that will be prepended to any URLs generated by the subconfigurator's add_route names route_prefix does not touch the names. So you'll want to name your routes "subapp1.route1" or "subapp1_route1" or such.

add_subscriber(subscriber, iface=None)

在 Pyramid 的事件循环中插入回调,以自定义它如何处理请求。“渲染器”一章有一个使用它的示例。

add_renderer(name, factory)

添加自定义渲染器。“渲染器”一章中有一个示例。

set_authentication_policy, set_authorization_policy, set_default_permission

配置 Pyramid 的内置授权机制。

Other methods sometimes used: add_notfound_viewadd_exception_viewset_request_factoryadd_tweenoverride_asset (used in theming). Add-ons can define additional config methods by calling config.add_directive .

路由参数

config.add_route accepts a large number of keyword arguments. They are logically divided into predicate argumets 和 non-predicate arguments. Predicate arguments determine whether the route matches the current request. All predicates must succeed in order for the route to be chosen. Non-predicate arguments do not affect whether the route matches.

名称

[非谓词]第一个位置参数;必需。这必须是路由的唯一名称。该名称用于在注册视图或生成URL时标识路由。

模式

[Predicate] The second positional arg; required. This is the URL path with optional "{variable}" placeholders; e.g., "/articles/{id}" or "/abc/{filename}.html". The leading slash is optional. By default the placeholder matches all characters up to a slash, but you can specify a regex to make it match less (e.g., "{variable:d+}" for a numeric variable) or more ("{variable:.*}" to match the entire rest of the URL including slashes). The substrings matched by the placeholders will be available as request.matchdict 在视野中。

A wildcard syntax "*varname" matches the rest of the URL and puts it into the matchdict as a tuple of segments instead of a single string. So a pattern "/foo/{action}/*fizzle" would match a URL "/foo/edit/a/1" and produce a matchdict {{'action': u'edit', 'fizzle': (u'a', u'1')}} .

存在两个特殊的通配符,“遍历”和“子路径”。这些在高级情况下用于对URL的其余部分进行遍历。

对于反斜杠(d)的正则表达式,XXX应该使用原始字符串语法?

request_method

[谓词]HTTP方法:“get”、“post”、“head”、“delete”、“put”。只有此类型的请求才会与路由匹配。

request_param

[谓词]如果值不包含“=”(例如,“q”),则请求必须具有指定的参数(g e t或post变量)。如果它包含“=”(例如,“name=value”),参数也必须具有指定的值。

This is especially useful when tunnelling other HTTP methods via POST. Web browsers can't submit a PUT or DELETE method via a form, so it's customary to use POST and to set a parameter _method="PUT" . The framework or application sees the "_method" parameter and pretends the other HTTP method was requested. In Pyramid you can do this with request_param="_method=PUT .

XHR

[谓词]如果请求必须有“x-requested-with”头,则为true。一些javascript库(jquery、prototype等)在Ajax请求中设置了这个头部,以将它们与用户启动的浏览器请求区分开来。

custom_predicates

[Predicate] A sequence of callables which will be called to determine whether the route matches the request. Use this feature if none of the other predicate arguments do what you need. The request will match the route only if all callables return True . Each callable will receive two arguments, inforequest . request is the current request. info is a dict containing the following:

info["match"]  =>  the match dict for the current route
info["route"].name  =>  the name of the current route
info["route"].pattern  =>  the URL pattern of the current route

您可以修改match dict以影响视图的查看方式。例如,您可以根据模型对象的ID查找它,并将该对象放在另一个键下的match dict中。如果在模型中找不到记录,则可以返回false。

其他可用参数:accept、factory、header、path_info、traverse。