ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2739

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

32.1. CONFLICT DETECTION

There are two statements which conflict, shown beneath the For: line: config.add_view(hello_world. ’hello’) on line 14 of app.py, and config.add_view(goodbye_world, ’hello’) on line 17 of app.py.

These two configuration statements are in conflict because we’ve tried to tell the system that the set of predicate values for both view configurations are exactly the same. Both the hello_world and goodbye_world views are configured to respond under the same set of circumstances. This circumstance: the view name (represented by the name= predicate) is hello.

This presents an ambiguity that Pyramid cannot resolve. Rather than allowing the circumstance to go unreported, by default Pyramid raises a ConfigurationConflictError error and prevents the application from running.

Conflict detection happens for any kind of configuration: imperative configuration or configuration that results from the execution of a scan.

32.1.1 Manually Resolving Conflicts

There are a number of ways to manually resolve conflicts: by changing registrations to not conflict, by strategically using pyramid.config.Configurator.commit(), or by using an “autocommitting” configurator.

The Right Thing

The most correct way to resolve conflicts is to “do the needful”: change your configuration code to not have conflicting configuration statements. The details of how this is done depends entirely on the configuration statements made by your application. Use the detail provided in the ConfigurationConflictError to track down the offending conflicts and modify your configuration code accordingly.

If you’re getting a conflict while trying to extend an existing application, and that application has a function which performs configuration like this one:

1 def add_routes(config):

2config.add_route(...)

Don’t call this function directly with config as an argument. Instead, use pyramid.config.Configuration.include():

363

32. ADVANCED CONFIGURATION

1 config.include(add_routes)

Using include() instead of calling the function directly provides a modicum of automated conflict resolution, with the configuration statements you define in the calling code overriding those of the included function. See also Automatic Conflict Resolution and Including Configuration from External Sources.

Using config.commit()

You can manually commit a configuration by using the commit() method between configuration calls. For example, we prevent conflicts from occurring in the application we examined previously as the result of adding a commit. Here’s the application that generates conflicts:

1 from wsgiref.simple_server import make_server

2 from pyramid.config import Configurator

3 from pyramid.response import Response

4

5 def hello_world(request):

6return Response(’Hello world!’)

7

8 def goodbye_world(request):

9return Response(’Goodbye world!’)

10

11if __name__ == ’__main__’:

12config = Configurator()

13

14 config.add_view(hello_world, name=’hello’)

15

16# conflicting view configuration

17config.add_view(goodbye_world, name=’hello’)

18

19app = config.make_wsgi_app()

20server = make_server(’0.0.0.0’, 8080, app)

21server.serve_forever()

We can prevent the two add_view calls from conflicting by issuing a call to commit() between them:

1

2

3

4

5

from wsgiref.simple_server import make_server from pyramid.config import Configurator

from pyramid.response import Response

def hello_world(request):

364


32.1. CONFLICT DETECTION

6return Response(’Hello world!’)

7

8 def goodbye_world(request):

9return Response(’Goodbye world!’)

10

11if __name__ == ’__main__’:

12config = Configurator()

13

14 config.add_view(hello_world, name=’hello’)

15

16 config.commit() # commit any pending configuration actions

17

18# no-longer-conflicting view configuration

19config.add_view(goodbye_world, name=’hello’)

20

21app = config.make_wsgi_app()

22server = make_server(’0.0.0.0’, 8080, app)

23server.serve_forever()

In the above example we’ve issued a call to commit() between the two add_view calls. commit() will execute any pending configuration statements.

Calling commit() is safe at any time. It executes all pending configuration actions and leaves the configuration action list “clean”.

Note that commit() has no effect when you’re using an autocommitting configurator (see Using An Autocommitting Configurator).

Using An Autocommitting Configurator

You can also use a heavy hammer to circumvent conflict detection by using a configurator constructor parameter: autocommit=True. For example:

1

2

3

4

from pyramid.config import Configurator

if __name__ == ’__main__’:

config = Configurator(autocommit=True)

When the autocommit parameter passed to the Configurator is True, conflict detection (and TwoPhase Configuration) is disabled. Configuration statements will be executed immediately, and succeeding statements will override preceding ones.

commit() has no effect when autocommit is True.

If you use a Configurator in code that performs unit testing, it’s usually a good idea to use an autocommitting Configurator, because you are usually unconcerned about conflict detection or two-phase configuration in test code.

365


32. ADVANCED CONFIGURATION

32.1.2 Automatic Conflict Resolution

If your code uses the include() method to include external configuration, some conflicts are automatically resolved. Configuration statements that are made as the result of an “include” will be overridden by configuration statements that happen within the caller of the “include” method.

Automatic conflict resolution supports this goal: if a user wants to reuse a Pyramid application, and they want to customize the configuration of this application without hacking its code “from outside”, they can “include” a configuration function from the package and override only some of its configuration statements within the code that does the include. No conflicts will be generated by configuration statements within the code which does the including, even if configuration statements in the included code would conflict if it was moved “up” to the calling code.

32.1.3 Methods Which Provide Conflict Detection

These are the methods of the configurator which provide conflict detection:

add_view(), add_route(), add_renderer(), set_request_factory(), set_session_factory(), set_request_property(), set_root_factory(), set_view_mapper(), set_authentication_policy(), set_authorization_policy(), set_renderer_globals_factory(), set_locale_negotiator(), set_default_permission(), add_traverser(), add_resource_url_adapter(), and add_response_adapter().

add_static_view() also indirectly provides conflict detection, because it’s implemented in terms of the conflict-aware add_route and add_view methods.

32.2 Including Configuration from External Sources

Some application programmers will factor their configuration code in such a way that it is easy to reuse and override configuration statements. For example, such a developer might factor out a function used to add routes to his application:

1 def add_routes(config):

2config.add_route(...)

Rather than calling this function directly with config as an argument. Instead, use pyramid.config.Configuration.include():

366


32.3. TWO-PHASE CONFIGURATION

1 config.include(add_routes)

Using include rather than calling the function directly will allow Automatic Conflict Resolution to work.

include() can also accept a module as an argument:

1

2

3

import myapp

config.include(myapp)

For this to work properly, the myapp module must contain a callable with the special name includeme, which should perform configuration (like the add_routes callable we showed above as an example).

include() can also accept a dotted Python name to a function or a module.

32.3 Two-Phase Configuration

When a non-autocommitting Configurator is used to do configuration (the default), configuration execution happens in two phases. In the first phase, “eager” configuration actions (actions that must happen before all others, such as registering a renderer) are executed, and discriminators are computed for each of the actions that depend on the result of the eager actions. In the second phase, the discriminators of all actions are compared to do conflict detection.

Due to this, for configuration methods that have no internal ordering constraints, execution order of configuration method calls is not important. For example, the relative ordering of add_view() and add_renderer() is unimportant when a non-autocommitting configurator is used. This code snippet:

1 config.add_view(’some.view’, renderer=’path_to_custom/renderer.rn’) 2 config.add_renderer(’.rn’, SomeCustomRendererFactory)

Has the same result as:

1

config.add_renderer(’.rn’, SomeCustomRendererFactory)

2

config.add_view(’some.view’, renderer=’path_to_custom/renderer.rn’)

 

 

367

32. ADVANCED CONFIGURATION

Even though the view statement depends on the registration of a custom renderer, due to two-phase configuration, the order in which the configuration statements are issued is not important. add_view will be able to find the .rn renderer even if add_renderer is called after add_view.

The same is untrue when you use an autocommitting configurator (see Using An Autocommitting Configurator). When an autocommitting configurator is used, two-phase configuration is disabled, and configuration statements must be ordered in dependency order.

Some configuration methods, such as add_route() have internal ordering constraints: the routes they imply require relative ordering. Such ordering constraints are not absolved by two-phase configuration. Routes are still added in configuration execution order.

368


CHAPTER

THIRTYTHREE

EXTENDING PYRAMID

CONFIGURATION

Pyramid allows you to extend its Configurator with custom directives. Custom directives can use other directives, they can add a custom action, they can participate in conflict resolution, and they can provide some number of introspectable objects.

33.1 Adding Methods to the Configurator via add_directive

Framework extension writers can add arbitrary methods to a Configurator by using the pyramid.config.Configurator.add_directive() method of the configurator. Using add_directive() makes it possible to extend a Pyramid configurator in arbitrary ways, and allows it to perform application-specific tasks more succinctly.

The add_directive() method accepts two positional arguments: a method name and a callable object. The callable object is usually a function that takes the configurator instance as its first argument and accepts other arbitrary positional and keyword arguments. For example:

1

from

pyramid.events

import

NewRequest

2

from

pyramid.config

import

Configurator

3

4 def add_newrequest_subscriber(config, subscriber):

5config.add_subscriber(subscriber, NewRequest)

6

7 if __name__ == ’__main__’:

8config = Configurator()

9config.add_directive(’add_newrequest_subscriber’,

10

add_newrequest_subscriber)

369

33. EXTENDING PYRAMID CONFIGURATION

Once add_directive() is called, a user can then call the added directive by its given name as if it were a built-in method of the Configurator:

1

2

3

4

def mysubscriber(event): print event.request

config.add_newrequest_subscriber(mysubscriber)

A call to add_directive() is often “hidden” within an includeme function within a “frameworky” package meant to be included as per Including Configuration from External Sources via include(). For example, if you put this code in a package named pyramid_subscriberhelpers:

1

2

3

def includeme(config): config.add_directive(’add_newrequest_subscriber’,

add_newrequest_subscriber)

The user of the add-on package pyramid_subscriberhelpers would then be able to install it and subsequently do:

1

2

3

4

5

6

7

def mysubscriber(event): print event.request

from pyramid.config import Configurator config = Configurator() config.include(’pyramid_subscriberhelpers’)

config.add_newrequest_subscriber(mysubscriber)

33.2 Using config.action in a Directive

If a custom directive can’t do its work exclusively in terms of existing configurator methods (such as pyramid.config.Configurator.add_subscriber(), as above), the directive may need to make use of the pyramid.config.Configurator.action() method. This method adds an entry to the list of “actions” that Pyramid will attempt to process when pyramid.config.Configurator.commit() is called. An action is simply a dictionary that includes a discriminator, possibly a callback function, and possibly other metadata used by Pyramid’s action system.

Here’s an example directive which uses the “action” method:

370