Debian Codegraph @

docs/source/contextlocals.rst

raw
1 .. _contextlocals:
2
3
4 Context/Thread-Locals vs. Explicit Argument Passing
5 ===================================================
6 In any pecan application, the module-level ``pecan.request`` and
7 ``pecan.response`` are proxy objects that always refer to the request and
8 response being handled in the current thread.
9
10 This `thread locality` ensures that you can safely access a global reference to
11 the current request and response in a multi-threaded environment without
12 constantly having to pass object references around in your code; it's a feature
13 of pecan that makes writing traditional web applications easier and less
14 verbose.
15
16 Some people feel thread-locals are too implicit or magical, and that explicit
17 reference passing is much clearer and more maintainable in the long run.
18 Additionally, the default implementation provided by pecan uses
19 :func:`threading.local` to associate these context-local proxy objects with the
20 `thread identifier` of the current server thread. In asynchronous server
21 models - where lots of tasks run for short amounts of time on
22 a `single` shared thread - supporting this mechanism involves monkeypatching
23 :func:`threading.local` to behave in a greenlet-local manner.
24
25 Disabling Thread-Local Proxies
26 ------------------------------
27
28 If you're certain that you `do not` want to utilize context/thread-locals in
29 your project, you can do so by passing the argument
30 ``use_context_locals=False`` in your application's configuration file::
31
32 app = {
33 'root': 'project.controllers.root.RootController',
34 'modules': ['project'],
35 'static_root': '%(confdir)s/public',
36 'template_path': '%(confdir)s/project/templates',
37 'debug': True,
38 'use_context_locals': False
39 }
40
41 Additionally, you'll need to update **all** of your pecan controllers to accept
42 positional arguments for the current request and response::
43
44 class RootController(object):
45
46 @pecan.expose('json')
47 def index(self, req, resp):
48 return dict(method=req.method) # path: /
49
50 @pecan.expose()
51 def greet(self, req, resp, name):
52 return name # path: /greet/joe
53
54 It is *imperative* that the request and response arguments come **after**
55 ``self`` and before any positional form arguments.