Debian Codegraph @

pecan/decorators.py

raw
1 from inspect import getmembers, isclass, isfunction
2
3 from .util import _cfg, getargspec
4
5 __all__ = [
6 'expose', 'transactional', 'accept_noncanonical', 'after_commit',
7 'after_rollback'
8 ]
9
10
11 def when_for(controller):
12 def when(method, **kw):
13 def decorate(f):
14 _cfg(f)['generic_handler'] = True
15 controller._pecan['generic_handlers'][method.upper()] = f
16 controller._pecan['allowed_methods'].append(method.upper())
17 expose(**kw)(f)
18 return f
19 return decorate
20 return when
21
22
23 def expose(template=None,
24 generic=False,
25 route=None,
26 **kw):
27
28 '''
29 Decorator used to flag controller methods as being "exposed" for
30 access via HTTP, and to configure that access.
31
32 :param template: The path to a template, relative to the base template
33 directory. Can also be passed a string representing
34 a special or custom renderer, such as ``'json'`` for
35 :ref:`expose_json`.
36 :param content_type: The content-type to use for this template.
37 :param generic: A boolean which flags this as a "generic" controller,
38 which uses generic functions based upon
39 ``functools.singledispatch`` generic functions. Allows you
40 to split a single controller into multiple paths based upon
41 HTTP method.
42 :param route: The name of the path segment to match (excluding
43 separator characters, like `/`). Defaults to the name of
44 the function itself, but this can be used to resolve paths
45 which are not valid Python function names, e.g., if you
46 wanted to route a function to `some-special-path'.
47 '''
48
49 content_type = kw.get('content_type', 'text/html')
50
51 if template == 'json':
52 content_type = 'application/json'
53
54 def decorate(f):
55 # flag the method as exposed
56 f.exposed = True
57
58 cfg = _cfg(f)
59 cfg['explicit_content_type'] = 'content_type' in kw
60
61 if route:
62 # This import is here to avoid a circular import issue
63 from pecan import routing
64 if cfg.get('generic_handler'):
65 raise ValueError(
66 'Path segments cannot be overridden for generic '
67 'controllers.'
68 )
69 routing.route(route, f)
70
71 # set a "pecan" attribute, where we will store details
72 cfg['content_type'] = content_type
73 cfg.setdefault('template', []).append(template)
74 cfg.setdefault('content_types', {})[content_type] = template
75
76 # handle generic controllers
77 if generic:
78 if f.__name__ in ('_default', '_lookup', '_route'):
79 raise ValueError(
80 'The special method %s cannot be used as a generic '
81 'controller' % f.__name__
82 )
83 cfg['generic'] = True
84 cfg['generic_handlers'] = dict(DEFAULT=f)
85 cfg['allowed_methods'] = []
86 f.when = when_for(f)
87
88 # store the arguments for this controller method
89 cfg['argspec'] = getargspec(f)
90
91 return f
92
93 return decorate
94
95
96 def transactional(ignore_redirects=True):
97 '''
98 If utilizing the :mod:`pecan.hooks` ``TransactionHook``, allows you
99 to flag a controller method or class as being wrapped in a transaction,
100 regardless of HTTP method.
101
102 :param ignore_redirects: Indicates if the hook should ignore redirects
103 for this controller or not.
104 '''
105
106 def deco(f):
107 if isclass(f):
108 for meth in [
109 m[1] for m in getmembers(f)
110 if isfunction(m[1])
111 ]:
112 if getattr(meth, 'exposed', False):
113 _cfg(meth)['transactional'] = True
114 _cfg(meth)['transactional_ignore_redirects'] = _cfg(
115 meth
116 ).get(
117 'transactional_ignore_redirects',
118 ignore_redirects
119 )
120 else:
121 _cfg(f)['transactional'] = True
122 _cfg(f)['transactional_ignore_redirects'] = ignore_redirects
123 return f
124 return deco
125
126
127 def after_action(action_type, action):
128 '''
129 If utilizing the :mod:`pecan.hooks` ``TransactionHook``, allows you
130 to flag a controller method to perform a callable action after the
131 action_type is successfully issued.
132
133 :param action: The callable to call after the commit is successfully
134 issued. '''
135
136 if action_type not in ('commit', 'rollback'):
137 raise Exception('action_type (%s) is not valid' % action_type)
138
139 def deco(func):
140 _cfg(func).setdefault('after_%s' % action_type, []).append(action)
141 return func
142 return deco
143
144
145 def after_commit(action):
146 '''
147 If utilizing the :mod:`pecan.hooks` ``TransactionHook``, allows you
148 to flag a controller method to perform a callable action after the
149 commit is successfully issued.
150
151 :param action: The callable to call after the commit is successfully
152 issued.
153 '''
154 return after_action('commit', action)
155
156
157 def after_rollback(action):
158 '''
159 If utilizing the :mod:`pecan.hooks` ``TransactionHook``, allows you
160 to flag a controller method to perform a callable action after the
161 rollback is successfully issued.
162
163 :param action: The callable to call after the rollback is successfully
164 issued.
165 '''
166 return after_action('rollback', action)
167
168
169 def accept_noncanonical(func):
170 '''
171 Flags a controller method as accepting non-canoncial URLs.
172 '''
173
174 _cfg(func)['accept_noncanonical'] = True
175 return func