Debian Codegraph @

pecan/middleware/recursive.py

raw
1 # (c) 2005 Ian Bicking and contributors; written for Paste
2 # Licensed under the MIT license:
3 # http://www.opensource.org/licenses/mit-license.php
4
5 """
6 Middleware to make internal requests and forward requests internally.
7
8 Raise ``ForwardRequestException(new_path_info)`` to do a forward
9 (aborting the current request).
10 """
11
12 __all__ = ['RecursiveMiddleware']
13
14
15 class RecursionLoop(AssertionError):
16 # Subclasses AssertionError for legacy reasons
17 """Raised when a recursion enters into a loop"""
18
19
20 class CheckForRecursionMiddleware(object):
21 def __init__(self, app, env):
22 self.app = app
23 self.env = env
24
25 def __call__(self, environ, start_response):
26 path_info = environ.get('PATH_INFO', '')
27 if path_info in self.env.get('pecan.recursive.old_path_info', []):
28 raise RecursionLoop(
29 "Forwarding loop detected; %r visited twice (internal "
30 "redirect path: %s)"
31 % (path_info, self.env['pecan.recursive.old_path_info'])
32 )
33 old_path_info = self.env.setdefault(
34 'pecan.recursive.old_path_info', []
35 )
36 old_path_info.append(self.env.get('PATH_INFO', ''))
37 return self.app(environ, start_response)
38
39
40 class RecursiveMiddleware(object):
41
42 """
43 A WSGI middleware that allows for recursive and forwarded calls.
44 All these calls go to the same 'application', but presumably that
45 application acts differently with different URLs. The forwarded
46 URLs must be relative to this container.
47 """
48
49 def __init__(self, application, global_conf=None):
50 self.application = application
51
52 def __call__(self, environ, start_response):
53 my_script_name = environ.get('SCRIPT_NAME', '')
54 environ['pecan.recursive.script_name'] = my_script_name
55 try:
56 return self.application(environ, start_response)
57 except ForwardRequestException as e:
58 middleware = CheckForRecursionMiddleware(
59 e.factory(self), environ)
60 return middleware(environ, start_response)
61
62
63 class ForwardRequestException(Exception):
64 """
65 Used to signal that a request should be forwarded to a different location.
66
67 ``url``
68 The URL to forward to starting with a ``/`` and relative to
69 ``RecursiveMiddleware``. URL fragments can also contain query strings
70 so ``/error?code=404`` would be a valid URL fragment.
71
72 ``environ``
73 An altertative WSGI environment dictionary to use for the forwarded
74 request. If specified is used *instead* of the ``url_fragment``
75
76 ``factory``
77 If specifed ``factory`` is used instead of ``url`` or ``environ``.
78 ``factory`` is a callable that takes a WSGI application object
79 as the first argument and returns an initialised WSGI middleware
80 which can alter the forwarded response.
81
82 Basic usage (must have ``RecursiveMiddleware`` present) :
83
84 .. code-block:: python
85
86 from pecan.middleware.recursive import ForwardRequestException
87 def app(environ, start_response):
88 if environ['PATH_INFO'] == '/hello':
89 start_response("200 OK", [('Content-type', 'text/plain')])
90 return ['Hello World!']
91 elif environ['PATH_INFO'] == '/error':
92 start_response("404 Not Found",
93 [('Content-type', 'text/plain')]
94 )
95 return ['Page not found']
96 else:
97 raise ForwardRequestException('/error')
98
99 from pecan.middleware.recursive import RecursiveMiddleware
100 app = RecursiveMiddleware(app)
101
102 If you ran this application and visited ``/hello`` you would get a
103 ``Hello World!`` message. If you ran the application and visited
104 ``/not_found`` a ``ForwardRequestException`` would be raised and the caught
105 by the ``RecursiveMiddleware``. The ``RecursiveMiddleware`` would then
106 return the headers and response from the ``/error`` URL but would display
107 a ``404 Not found`` status message.
108
109 You could also specify an ``environ`` dictionary instead of a url. Using
110 the same example as before:
111
112 .. code-block:: python
113
114 def app(environ, start_response):
115 ... same as previous example ...
116 else:
117 new_environ = environ.copy()
118 new_environ['PATH_INFO'] = '/error'
119 raise ForwardRequestException(environ=new_environ)
120 """
121
122 def __init__(self, url=None, environ=None, factory=None, path_info=None):
123 environ = environ or {}
124 # Check no incompatible options have been chosen
125 if factory and url:
126 raise TypeError(
127 'You cannot specify factory and a url in '
128 'ForwardRequestException'
129 ) # pragma: nocover
130 elif factory and environ:
131 raise TypeError(
132 'You cannot specify factory and environ in '
133 'ForwardRequestException'
134 ) # pragma: nocover
135 if url and environ:
136 raise TypeError(
137 'You cannot specify environ and url in '
138 'ForwardRequestException'
139 ) # pragma: nocover
140
141 # set the path_info or warn about its use.
142 if path_info:
143 self.path_info = path_info
144
145 # If the url can be treated as a path_info do that
146 if url and '?' not in str(url):
147 self.path_info = url
148
149 # Base middleware
150 class ForwardRequestExceptionMiddleware(object):
151 def __init__(self, app):
152 self.app = app
153
154 # Otherwise construct the appropriate middleware factory
155 if hasattr(self, 'path_info'):
156 p = self.path_info
157
158 def factory_pi(app):
159 class PathInfoForward(ForwardRequestExceptionMiddleware):
160 def __call__(self, environ, start_response):
161 environ['PATH_INFO'] = p
162 return self.app(environ, start_response)
163 return PathInfoForward(app)
164
165 self.factory = factory_pi
166 elif url:
167 def factory_url(app):
168 class URLForward(ForwardRequestExceptionMiddleware):
169 def __call__(self, environ, start_response):
170 environ['PATH_INFO'] = url.split('?')[0]
171 environ['QUERY_STRING'] = url.split('?')[1]
172 return self.app(environ, start_response)
173 return URLForward(app)
174
175 self.factory = factory_url
176 elif environ:
177 def factory_env(app):
178 class EnvironForward(ForwardRequestExceptionMiddleware):
179 def __call__(self, environ_, start_response):
180 return self.app(environ, start_response)
181 return EnvironForward(app)
182
183 self.factory = factory_env
184 else:
185 self.factory = factory