应用程序配置

大多数人已经将“配置”理解为影响应用程序操作的设置。例如,很容易想到 .ini 在应用程序启动时解析为“配置”的文件。但是,如果你思想相当开放,很容易想到 code 配置也一样。因为和大多数其他Web应用程序平台一样,金字塔是 框架 它调用您编写的代码(而不是 类库 ,这是纯粹为您调用而存在的代码)。插入已写入的应用程序代码的行为 Pyramid 在本文档中也称为“配置”;您正在配置 Pyramid 调用组成应用程序的代码。

参见

有关的信息 .ini 金字塔应用程序的文件请参见 启动 章。

有两种方法可以配置 Pyramid 应用: imperative configurationdeclarative configuration . 这两个都在下面描述。

命令式配置

“命令式配置”只是指由python语句完成的配置,一个接一个。这里有一个最简单的 Pyramid 应用程序,强制配置:

 1from wsgiref.simple_server import make_server
 2from pyramid.config import Configurator
 3from pyramid.response import Response
 4
 5def hello_world(request):
 6    return Response('Hello world!')
 7
 8if __name__ == '__main__':
 9    with Configurator() as config:
10        config.add_route('hello', '/')
11        config.add_view(hello_world, route_name='hello')
12        app = config.make_wsgi_app()
13    server = make_server('0.0.0.0', 6543, app)
14    server.serve_forever()

我们还不会谈论这个应用程序的功能。请注意,配置语句发生在 if __name__ == '__main__': 方法调用形式的节 Configurator 对象(例如, config.add_view(...) )这些语句一个接一个地发生,并按顺序执行,因此可以在这种配置模式中使用Python的全部功能,包括条件。

声明性配置

有时用命令式代码完成所有配置会很痛苦,因为通常单个应用程序的代码可能存在于许多文件中。如果配置集中在一个地方,则需要同时打开至少两个文件才能看到“大画面”:表示配置的文件,以及包含由配置引用的实现对象的文件。为了避免这种情况, Pyramid 允许插入 configuration decoration 与声明本身引用的代码非常接近的语句。例如:

1from pyramid.response import Response
2from pyramid.view import view_config
3
4@view_config(route_name='hello', request_method='GET')
5def hello_world(request):
6    return Response('Hello World!')

仅存在配置装饰不会导致执行任何配置注册。在它对 Pyramid 应用程序,应用程序代码中的配置修饰必须通过称为 scan .

例如, pyramid.view.view_config 上面代码示例中的decorator向 hello_world 函数,使其可用于 scan 以后再找。

A scan A的 module 或A package 它的装饰子包装发生在 pyramid.config.Configurator.scan() 方法被调用:扫描意味着在包及其子包中搜索配置声明。例如:

 1from wsgiref.simple_server import make_server
 2from pyramid.config import Configurator
 3from pyramid.response import Response
 4from pyramid.view import view_config
 5
 6
 7@view_config(route_name='hello', request_method='GET')
 8def hello_world(request):
 9    return Response('Hello World!')
10
11
12if __name__ == '__main__':
13    with Configurator() as config:
14        config.add_route('hello', '/')
15        config.scan()
16        app = config.make_wsgi_app()
17    server = make_server('0.0.0.0', 6543, app)
18    server.serve_forever()

扫描机器递归地导入包或模块中的每个模块和子包,查找附加到模块内定义的对象的特殊属性。这些特殊属性通常通过使用 decorator . 例如, view_config decorator可以附加到函数或实例方法。

一旦调用扫描,并且 configuration decoration 是由扫描仪找到的,对 Configurator 代表你。这些调用取代了添加命令式配置语句的需要,这些命令式配置语句不靠近正在配置的代码。

结合 configuration decoration 以及 scan 合称为 declarative configuration .

在上面的示例中,扫描程序将参数转换为 view_config 打电话给 pyramid.config.Configurator.add_view() 方法,有效:

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

总结

有两种方法可以配置 Pyramid 应用:声明性和强制性。您可以选择最舒适的模式;两者完全相同。本文档中的示例将交替使用这两种模式。