cavisson-pythonagent 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. cavisson_pythonagent-0.0.1.dist-info/METADATA +32 -0
  2. cavisson_pythonagent-0.0.1.dist-info/RECORD +180 -0
  3. cavisson_pythonagent-0.0.1.dist-info/WHEEL +5 -0
  4. cavisson_pythonagent-0.0.1.dist-info/licenses/LICENSE +19 -0
  5. cavisson_pythonagent-0.0.1.dist-info/top_level.txt +1 -0
  6. pythonagent/__init__.py +22 -0
  7. pythonagent/agent/__init__.py +219 -0
  8. pythonagent/agent/internal/__init__.py +1 -0
  9. pythonagent/agent/internal/agent.py +1651 -0
  10. pythonagent/agent/internal/framesinfo.py +152 -0
  11. pythonagent/agent/internal/heap_dump.py +39 -0
  12. pythonagent/agent/internal/intercept_module.py +70 -0
  13. pythonagent/agent/internal/logs.py +122 -0
  14. pythonagent/agent/internal/metadata/__init__.py +0 -0
  15. pythonagent/agent/internal/metadata/agent_meta_data.py +276 -0
  16. pythonagent/agent/internal/proc_compat.py +75 -0
  17. pythonagent/agent/internal/profile.py +47 -0
  18. pythonagent/agent/internal/provider.py +83 -0
  19. pythonagent/agent/internal/thread_dump.py +85 -0
  20. pythonagent/agent/internal/udp.py +245 -0
  21. pythonagent/agent/internal/udp_message.py +800 -0
  22. pythonagent/agent/probes/Instrumentation/__init__.py +340 -0
  23. pythonagent/agent/probes/Instrumentation/find.py +243 -0
  24. pythonagent/agent/probes/Instrumentation/module_version_resolver.py +155 -0
  25. pythonagent/agent/probes/Instrumentation/new_parser.py +64 -0
  26. pythonagent/agent/probes/Instrumentation/parser.py +129 -0
  27. pythonagent/agent/probes/__init__.py +219 -0
  28. pythonagent/agent/probes/base.py +303 -0
  29. pythonagent/agent/probes/cache/__init__.py +51 -0
  30. pythonagent/agent/probes/cache/redis.py +119 -0
  31. pythonagent/agent/probes/cache/redis_asyncio.py +83 -0
  32. pythonagent/agent/probes/coroutines/__init__.py +1 -0
  33. pythonagent/agent/probes/coroutines/asyncio.py +63 -0
  34. pythonagent/agent/probes/elasticdb/__init__.py +7 -0
  35. pythonagent/agent/probes/elasticdb/aelastic.py +54 -0
  36. pythonagent/agent/probes/frameworks/__init__.py +27 -0
  37. pythonagent/agent/probes/frameworks/agentprofiler.py +105 -0
  38. pythonagent/agent/probes/frameworks/aiohttp_web.py +155 -0
  39. pythonagent/agent/probes/frameworks/aisess.py +151 -0
  40. pythonagent/agent/probes/frameworks/asgi.py +340 -0
  41. pythonagent/agent/probes/frameworks/bottle.py +27 -0
  42. pythonagent/agent/probes/frameworks/cherry.py +25 -0
  43. pythonagent/agent/probes/frameworks/django.py +128 -0
  44. pythonagent/agent/probes/frameworks/falcon.py +21 -0
  45. pythonagent/agent/probes/frameworks/fastapi.py +35 -0
  46. pythonagent/agent/probes/frameworks/flask.py +30 -0
  47. pythonagent/agent/probes/frameworks/pyramid.py +56 -0
  48. pythonagent/agent/probes/frameworks/test.py +108 -0
  49. pythonagent/agent/probes/frameworks/tornado_async_web.py +117 -0
  50. pythonagent/agent/probes/frameworks/tornado_web.py +133 -0
  51. pythonagent/agent/probes/frameworks/wsgi.py +353 -0
  52. pythonagent/agent/probes/grpc/__init__.py +76 -0
  53. pythonagent/agent/probes/grpc/client_interceptor.py +132 -0
  54. pythonagent/agent/probes/grpc/server_interceptor.py +129 -0
  55. pythonagent/agent/probes/havoc/__init__.py +0 -0
  56. pythonagent/agent/probes/havoc/custom_memory_stress.py +186 -0
  57. pythonagent/agent/probes/havoc/custom_thread_stress.py +187 -0
  58. pythonagent/agent/probes/havoc/havoc_constants.py +218 -0
  59. pythonagent/agent/probes/havoc/havoc_manager.py +981 -0
  60. pythonagent/agent/probes/http/__init__.py +49 -0
  61. pythonagent/agent/probes/http/aiohttp_client.py +59 -0
  62. pythonagent/agent/probes/http/boto.py +12 -0
  63. pythonagent/agent/probes/http/httplib.py +110 -0
  64. pythonagent/agent/probes/http/httpx_client.py +116 -0
  65. pythonagent/agent/probes/http/requests.py +15 -0
  66. pythonagent/agent/probes/http/tornado_httpclient.py +85 -0
  67. pythonagent/agent/probes/http/urllib3.py +16 -0
  68. pythonagent/agent/probes/langchain/__init__.py +21 -0
  69. pythonagent/agent/probes/langchain/base_tool.py +95 -0
  70. pythonagent/agent/probes/langchain/langchain_community.py +136 -0
  71. pythonagent/agent/probes/langchain/langchain_core.py +32 -0
  72. pythonagent/agent/probes/langchain/langchain_openai.py +110 -0
  73. pythonagent/agent/probes/logging/__init__.py +106 -0
  74. pythonagent/agent/probes/message_brokers/__init__.py +4 -0
  75. pythonagent/agent/probes/message_brokers/pika.py +126 -0
  76. pythonagent/agent/probes/mongodb/__init__.py +6 -0
  77. pythonagent/agent/probes/mongodb/pymongo.py +286 -0
  78. pythonagent/agent/probes/openai/__init__.py +3 -0
  79. pythonagent/agent/probes/openai/openai.py +797 -0
  80. pythonagent/agent/probes/span.py +101 -0
  81. pythonagent/agent/probes/sql/__init__.py +13 -0
  82. pythonagent/agent/probes/sql/botocores3.py +51 -0
  83. pythonagent/agent/probes/sql/dbapi.py +285 -0
  84. pythonagent/agent/probes/sql/dynamodb.py +90 -0
  85. pythonagent/agent/probes/sql/mysql_connector.py +24 -0
  86. pythonagent/agent/probes/sql/mysql_connector_cext.py +24 -0
  87. pythonagent/agent/probes/sql/mysqldb.py +43 -0
  88. pythonagent/agent/probes/sql/psycopg2.py +174 -0
  89. pythonagent/agent/probes/sql/pymysql.py +25 -0
  90. pythonagent/bootstrap/__init__.py +0 -0
  91. pythonagent/bootstrap/cav_gunicorn.py +26 -0
  92. pythonagent/bootstrap/cavagent_lambda_wrapper.py +291 -0
  93. pythonagent/bootstrap/run.py +47 -0
  94. pythonagent/bootstrap/sitecustomize.py +287 -0
  95. pythonagent/cavisson/netdiagnostics/CavAgent/instrumentationprofile.json +26 -0
  96. pythonagent/cavisson/netdiagnostics/CavAgent/interceptor_points.txt +29 -0
  97. pythonagent/cavisson/netdiagnostics/python/CavAgent/instrumentationprofile.json +42 -0
  98. pythonagent/cavisson/netdiagnostics/python/CavAgent/interceptor_points.txt +29 -0
  99. pythonagent/cavisson/netdiagnostics/python/config/ndsettings.conf +6 -0
  100. pythonagent/config.py +279 -0
  101. pythonagent/find.py +72 -0
  102. pythonagent/find_mod_cls_name.py +54 -0
  103. pythonagent/lang.py +131 -0
  104. pythonagent/lib.py +91 -0
  105. pythonagent/main/__init__.py +0 -0
  106. pythonagent/main/pytrace/__init__.py +79 -0
  107. pythonagent/main/pytrace/commands/__init__.py +0 -0
  108. pythonagent/main/pytrace/commands/auto_discovery.py +25 -0
  109. pythonagent/main/pytrace/commands/run.py +401 -0
  110. pythonagent/main/pytrace/pytrace.py +133 -0
  111. pythonagent/main/wsgi.py +6 -0
  112. pythonagent/main.py +27 -0
  113. pythonagent/run.py +46 -0
  114. pythonagent/sqins.py +8 -0
  115. pythonagent/test.py +73 -0
  116. pythonagent/utils.py +168 -0
  117. pythonagent/vendor/__init__.py +0 -0
  118. pythonagent/vendor/pympler/__init__.py +1 -0
  119. pythonagent/vendor/pympler/asizeof.py +2810 -0
  120. pythonagent/vendor/pympler/charts.py +62 -0
  121. pythonagent/vendor/pympler/classtracker.py +590 -0
  122. pythonagent/vendor/pympler/classtracker_stats.py +780 -0
  123. pythonagent/vendor/pympler/garbagegraph.py +80 -0
  124. pythonagent/vendor/pympler/mprofile.py +97 -0
  125. pythonagent/vendor/pympler/muppy.py +275 -0
  126. pythonagent/vendor/pympler/panels.py +115 -0
  127. pythonagent/vendor/pympler/process.py +238 -0
  128. pythonagent/vendor/pympler/py.typed +0 -0
  129. pythonagent/vendor/pympler/refbrowser.py +451 -0
  130. pythonagent/vendor/pympler/refgraph.py +350 -0
  131. pythonagent/vendor/pympler/summary.py +321 -0
  132. pythonagent/vendor/pympler/tracker.py +267 -0
  133. pythonagent/vendor/pympler/util/__init__.py +0 -0
  134. pythonagent/vendor/pympler/util/bottle.py +3809 -0
  135. pythonagent/vendor/pympler/util/compat.py +23 -0
  136. pythonagent/vendor/pympler/util/stringutils.py +77 -0
  137. pythonagent/vendor/pympler/web.py +346 -0
  138. pythonagent/vendor/werkzeug/__init__.py +20 -0
  139. pythonagent/vendor/werkzeug/_compat.py +228 -0
  140. pythonagent/vendor/werkzeug/_internal.py +473 -0
  141. pythonagent/vendor/werkzeug/_reloader.py +341 -0
  142. pythonagent/vendor/werkzeug/datastructures.py +3120 -0
  143. pythonagent/vendor/werkzeug/debug/__init__.py +498 -0
  144. pythonagent/vendor/werkzeug/debug/console.py +218 -0
  145. pythonagent/vendor/werkzeug/debug/repr.py +297 -0
  146. pythonagent/vendor/werkzeug/debug/tbtools.py +628 -0
  147. pythonagent/vendor/werkzeug/exceptions.py +829 -0
  148. pythonagent/vendor/werkzeug/filesystem.py +64 -0
  149. pythonagent/vendor/werkzeug/formparser.py +584 -0
  150. pythonagent/vendor/werkzeug/http.py +1307 -0
  151. pythonagent/vendor/werkzeug/local.py +420 -0
  152. pythonagent/vendor/werkzeug/middleware/__init__.py +25 -0
  153. pythonagent/vendor/werkzeug/middleware/dispatcher.py +66 -0
  154. pythonagent/vendor/werkzeug/middleware/http_proxy.py +219 -0
  155. pythonagent/vendor/werkzeug/middleware/lint.py +408 -0
  156. pythonagent/vendor/werkzeug/middleware/profiler.py +132 -0
  157. pythonagent/vendor/werkzeug/middleware/proxy_fix.py +169 -0
  158. pythonagent/vendor/werkzeug/middleware/shared_data.py +293 -0
  159. pythonagent/vendor/werkzeug/posixemulation.py +117 -0
  160. pythonagent/vendor/werkzeug/routing.py +2210 -0
  161. pythonagent/vendor/werkzeug/security.py +249 -0
  162. pythonagent/vendor/werkzeug/serving.py +1117 -0
  163. pythonagent/vendor/werkzeug/test.py +1123 -0
  164. pythonagent/vendor/werkzeug/testapp.py +241 -0
  165. pythonagent/vendor/werkzeug/urls.py +1138 -0
  166. pythonagent/vendor/werkzeug/useragents.py +202 -0
  167. pythonagent/vendor/werkzeug/utils.py +778 -0
  168. pythonagent/vendor/werkzeug/wrappers/__init__.py +36 -0
  169. pythonagent/vendor/werkzeug/wrappers/accept.py +50 -0
  170. pythonagent/vendor/werkzeug/wrappers/auth.py +33 -0
  171. pythonagent/vendor/werkzeug/wrappers/base_request.py +673 -0
  172. pythonagent/vendor/werkzeug/wrappers/base_response.py +700 -0
  173. pythonagent/vendor/werkzeug/wrappers/common_descriptors.py +341 -0
  174. pythonagent/vendor/werkzeug/wrappers/cors.py +100 -0
  175. pythonagent/vendor/werkzeug/wrappers/etag.py +304 -0
  176. pythonagent/vendor/werkzeug/wrappers/json.py +145 -0
  177. pythonagent/vendor/werkzeug/wrappers/request.py +49 -0
  178. pythonagent/vendor/werkzeug/wrappers/response.py +84 -0
  179. pythonagent/vendor/werkzeug/wrappers/user_agent.py +14 -0
  180. pythonagent/vendor/werkzeug/wsgi.py +1000 -0
@@ -0,0 +1,2210 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ werkzeug.routing
4
+ ~~~~~~~~~~~~~~~~
5
+
6
+ When it comes to combining multiple controller or view functions (however
7
+ you want to call them) you need a dispatcher. A simple way would be
8
+ applying regular expression tests on the ``PATH_INFO`` and calling
9
+ registered callback functions that return the value then.
10
+
11
+ This module implements a much more powerful system than simple regular
12
+ expression matching because it can also convert values in the URLs and
13
+ build URLs.
14
+
15
+ Here a simple example that creates an URL map for an application with
16
+ two subdomains (www and kb) and some URL rules:
17
+
18
+ >>> m = Map([
19
+ ... # Static URLs
20
+ ... Rule('/', endpoint='static/index'),
21
+ ... Rule('/about', endpoint='static/about'),
22
+ ... Rule('/help', endpoint='static/help'),
23
+ ... # Knowledge Base
24
+ ... Subdomain('kb', [
25
+ ... Rule('/', endpoint='kb/index'),
26
+ ... Rule('/browse/', endpoint='kb/browse'),
27
+ ... Rule('/browse/<int:id>/', endpoint='kb/browse'),
28
+ ... Rule('/browse/<int:id>/<int:page>', endpoint='kb/browse')
29
+ ... ])
30
+ ... ], default_subdomain='www')
31
+
32
+ If the application doesn't use subdomains it's perfectly fine to not set
33
+ the default subdomain and not use the `Subdomain` rule factory. The endpoint
34
+ in the rules can be anything, for example import paths or unique
35
+ identifiers. The WSGI application can use those endpoints to get the
36
+ handler for that URL. It doesn't have to be a string at all but it's
37
+ recommended.
38
+
39
+ Now it's possible to create a URL adapter for one of the subdomains and
40
+ build URLs:
41
+
42
+ >>> c = m.bind('example.com')
43
+ >>> c.build("kb/browse", dict(id=42))
44
+ 'http://kb.example.com/browse/42/'
45
+ >>> c.build("kb/browse", dict())
46
+ 'http://kb.example.com/browse/'
47
+ >>> c.build("kb/browse", dict(id=42, page=3))
48
+ 'http://kb.example.com/browse/42/3'
49
+ >>> c.build("static/about")
50
+ '/about'
51
+ >>> c.build("static/index", force_external=True)
52
+ 'http://www.example.com/'
53
+
54
+ >>> c = m.bind('example.com', subdomain='kb')
55
+ >>> c.build("static/about")
56
+ 'http://www.example.com/about'
57
+
58
+ The first argument to bind is the server name *without* the subdomain.
59
+ Per default it will assume that the script is mounted on the root, but
60
+ often that's not the case so you can provide the real mount point as
61
+ second argument:
62
+
63
+ >>> c = m.bind('example.com', '/applications/example')
64
+
65
+ The third argument can be the subdomain, if not given the default
66
+ subdomain is used. For more details about binding have a look at the
67
+ documentation of the `MapAdapter`.
68
+
69
+ And here is how you can match URLs:
70
+
71
+ >>> c = m.bind('example.com')
72
+ >>> c.match("/")
73
+ ('static/index', {})
74
+ >>> c.match("/about")
75
+ ('static/about', {})
76
+ >>> c = m.bind('example.com', '/', 'kb')
77
+ >>> c.match("/")
78
+ ('kb/index', {})
79
+ >>> c.match("/browse/42/23")
80
+ ('kb/browse', {'id': 42, 'page': 23})
81
+
82
+ If matching fails you get a `NotFound` exception, if the rule thinks
83
+ it's a good idea to redirect (for example because the URL was defined
84
+ to have a slash at the end but the request was missing that slash) it
85
+ will raise a `RequestRedirect` exception. Both are subclasses of the
86
+ `HTTPException` so you can use those errors as responses in the
87
+ application.
88
+
89
+ If matching succeeded but the URL rule was incompatible to the given
90
+ method (for example there were only rules for `GET` and `HEAD` and
91
+ routing system tried to match a `POST` request) a `MethodNotAllowed`
92
+ exception is raised.
93
+
94
+
95
+ :copyright: 2007 Pallets
96
+ :license: BSD-3-Clause
97
+ """
98
+ import ast
99
+ import difflib
100
+ import posixpath
101
+ import re
102
+ import uuid
103
+ import warnings
104
+ from pprint import pformat
105
+ from threading import Lock
106
+
107
+ from ._compat import implements_to_string
108
+ from ._compat import iteritems
109
+ from ._compat import itervalues
110
+ from ._compat import native_string_result
111
+ from ._compat import string_types
112
+ from ._compat import text_type
113
+ from ._compat import to_bytes
114
+ from ._compat import to_unicode
115
+ from ._compat import wsgi_decoding_dance
116
+ from ._internal import _encode_idna
117
+ from ._internal import _get_environ
118
+ from .datastructures import ImmutableDict
119
+ from .datastructures import MultiDict
120
+ from .exceptions import BadHost
121
+ from .exceptions import BadRequest
122
+ from .exceptions import HTTPException
123
+ from .exceptions import MethodNotAllowed
124
+ from .exceptions import NotFound
125
+ from .urls import _fast_url_quote
126
+ from .urls import url_encode
127
+ from .urls import url_join
128
+ from .urls import url_quote
129
+ from .utils import cached_property
130
+ from .utils import format_string
131
+ from .utils import redirect
132
+ from .wsgi import get_host
133
+
134
+ _rule_re = re.compile(
135
+ r"""
136
+ (?P<static>[^<]*) # static rule data
137
+ <
138
+ (?:
139
+ (?P<converter>[a-zA-Z_][a-zA-Z0-9_]*) # converter name
140
+ (?:\((?P<args>.*?)\))? # converter arguments
141
+ \: # variable delimiter
142
+ )?
143
+ (?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name
144
+ >
145
+ """,
146
+ re.VERBOSE,
147
+ )
148
+ _simple_rule_re = re.compile(r"<([^>]+)>")
149
+ _converter_args_re = re.compile(
150
+ r"""
151
+ ((?P<name>\w+)\s*=\s*)?
152
+ (?P<value>
153
+ True|False|
154
+ \d+.\d+|
155
+ \d+.|
156
+ \d+|
157
+ [\w\d_.]+|
158
+ [urUR]?(?P<stringval>"[^"]*?"|'[^']*')
159
+ )\s*,
160
+ """,
161
+ re.VERBOSE | re.UNICODE,
162
+ )
163
+
164
+
165
+ _PYTHON_CONSTANTS = {"None": None, "True": True, "False": False}
166
+
167
+
168
+ def _pythonize(value):
169
+ if value in _PYTHON_CONSTANTS:
170
+ return _PYTHON_CONSTANTS[value]
171
+ for convert in int, float:
172
+ try:
173
+ return convert(value)
174
+ except ValueError:
175
+ pass
176
+ if value[:1] == value[-1:] and value[0] in "\"'":
177
+ value = value[1:-1]
178
+ return text_type(value)
179
+
180
+
181
+ def parse_converter_args(argstr):
182
+ argstr += ","
183
+ args = []
184
+ kwargs = {}
185
+
186
+ for item in _converter_args_re.finditer(argstr):
187
+ value = item.group("stringval")
188
+ if value is None:
189
+ value = item.group("value")
190
+ value = _pythonize(value)
191
+ if not item.group("name"):
192
+ args.append(value)
193
+ else:
194
+ name = item.group("name")
195
+ kwargs[name] = value
196
+
197
+ return tuple(args), kwargs
198
+
199
+
200
+ def parse_rule(rule):
201
+ """Parse a rule and return it as generator. Each iteration yields tuples
202
+ in the form ``(converter, arguments, variable)``. If the converter is
203
+ `None` it's a static url part, otherwise it's a dynamic one.
204
+
205
+ :internal:
206
+ """
207
+ pos = 0
208
+ end = len(rule)
209
+ do_match = _rule_re.match
210
+ used_names = set()
211
+ while pos < end:
212
+ m = do_match(rule, pos)
213
+ if m is None:
214
+ break
215
+ data = m.groupdict()
216
+ if data["static"]:
217
+ yield None, None, data["static"]
218
+ variable = data["variable"]
219
+ converter = data["converter"] or "default"
220
+ if variable in used_names:
221
+ raise ValueError("variable name %r used twice." % variable)
222
+ used_names.add(variable)
223
+ yield converter, data["args"] or None, variable
224
+ pos = m.end()
225
+ if pos < end:
226
+ remaining = rule[pos:]
227
+ if ">" in remaining or "<" in remaining:
228
+ raise ValueError("malformed url rule: %r" % rule)
229
+ yield None, None, remaining
230
+
231
+
232
+ class RoutingException(Exception):
233
+ """Special exceptions that require the application to redirect, notifying
234
+ about missing urls, etc.
235
+
236
+ :internal:
237
+ """
238
+
239
+
240
+ class RequestRedirect(HTTPException, RoutingException):
241
+ """Raise if the map requests a redirect. This is for example the case if
242
+ `strict_slashes` are activated and an url that requires a trailing slash.
243
+
244
+ The attribute `new_url` contains the absolute destination url.
245
+ """
246
+
247
+ code = 308
248
+
249
+ def __init__(self, new_url):
250
+ RoutingException.__init__(self, new_url)
251
+ self.new_url = new_url
252
+
253
+ def get_response(self, environ=None):
254
+ return redirect(self.new_url, self.code)
255
+
256
+
257
+ class RequestPath(RoutingException):
258
+ """Internal exception."""
259
+
260
+ __slots__ = ("path_info",)
261
+
262
+ def __init__(self, path_info):
263
+ self.path_info = path_info
264
+
265
+
266
+ class RequestAliasRedirect(RoutingException): # noqa: B903
267
+ """This rule is an alias and wants to redirect to the canonical URL."""
268
+
269
+ def __init__(self, matched_values):
270
+ self.matched_values = matched_values
271
+
272
+
273
+ @implements_to_string
274
+ class BuildError(RoutingException, LookupError):
275
+ """Raised if the build system cannot find a URL for an endpoint with the
276
+ values provided.
277
+ """
278
+
279
+ def __init__(self, endpoint, values, method, adapter=None):
280
+ LookupError.__init__(self, endpoint, values, method)
281
+ self.endpoint = endpoint
282
+ self.values = values
283
+ self.method = method
284
+ self.adapter = adapter
285
+
286
+ @cached_property
287
+ def suggested(self):
288
+ return self.closest_rule(self.adapter)
289
+
290
+ def closest_rule(self, adapter):
291
+ def _score_rule(rule):
292
+ return sum(
293
+ [
294
+ 0.98
295
+ * difflib.SequenceMatcher(
296
+ None, rule.endpoint, self.endpoint
297
+ ).ratio(),
298
+ 0.01 * bool(set(self.values or ()).issubset(rule.arguments)),
299
+ 0.01 * bool(rule.methods and self.method in rule.methods),
300
+ ]
301
+ )
302
+
303
+ if adapter and adapter.map._rules:
304
+ return max(adapter.map._rules, key=_score_rule)
305
+
306
+ def __str__(self):
307
+ message = []
308
+ message.append("Could not build url for endpoint %r" % self.endpoint)
309
+ if self.method:
310
+ message.append(" (%r)" % self.method)
311
+ if self.values:
312
+ message.append(" with values %r" % sorted(self.values.keys()))
313
+ message.append(".")
314
+ if self.suggested:
315
+ if self.endpoint == self.suggested.endpoint:
316
+ if self.method and self.method not in self.suggested.methods:
317
+ message.append(
318
+ " Did you mean to use methods %r?"
319
+ % sorted(self.suggested.methods)
320
+ )
321
+ missing_values = self.suggested.arguments.union(
322
+ set(self.suggested.defaults or ())
323
+ ) - set(self.values.keys())
324
+ if missing_values:
325
+ message.append(
326
+ " Did you forget to specify values %r?" % sorted(missing_values)
327
+ )
328
+ else:
329
+ message.append(" Did you mean %r instead?" % self.suggested.endpoint)
330
+ return u"".join(message)
331
+
332
+
333
+ class WebsocketMismatch(BadRequest):
334
+ """The only matched rule is either a WebSocket and the request is
335
+ HTTP, or the rule is HTTP and the request is a WebSocket.
336
+ """
337
+
338
+
339
+ class ValidationError(ValueError):
340
+ """Validation error. If a rule converter raises this exception the rule
341
+ does not match the current URL and the next URL is tried.
342
+ """
343
+
344
+
345
+ class RuleFactory(object):
346
+ """As soon as you have more complex URL setups it's a good idea to use rule
347
+ factories to avoid repetitive tasks. Some of them are builtin, others can
348
+ be added by subclassing `RuleFactory` and overriding `get_rules`.
349
+ """
350
+
351
+ def get_rules(self, map):
352
+ """Subclasses of `RuleFactory` have to override this method and return
353
+ an iterable of rules."""
354
+ raise NotImplementedError()
355
+
356
+
357
+ class Subdomain(RuleFactory):
358
+ """All URLs provided by this factory have the subdomain set to a
359
+ specific domain. For example if you want to use the subdomain for
360
+ the current language this can be a good setup::
361
+
362
+ url_map = Map([
363
+ Rule('/', endpoint='#select_language'),
364
+ Subdomain('<string(length=2):lang_code>', [
365
+ Rule('/', endpoint='index'),
366
+ Rule('/about', endpoint='about'),
367
+ Rule('/help', endpoint='help')
368
+ ])
369
+ ])
370
+
371
+ All the rules except for the ``'#select_language'`` endpoint will now
372
+ listen on a two letter long subdomain that holds the language code
373
+ for the current request.
374
+ """
375
+
376
+ def __init__(self, subdomain, rules):
377
+ self.subdomain = subdomain
378
+ self.rules = rules
379
+
380
+ def get_rules(self, map):
381
+ for rulefactory in self.rules:
382
+ for rule in rulefactory.get_rules(map):
383
+ rule = rule.empty()
384
+ rule.subdomain = self.subdomain
385
+ yield rule
386
+
387
+
388
+ class Submount(RuleFactory):
389
+ """Like `Subdomain` but prefixes the URL rule with a given string::
390
+
391
+ url_map = Map([
392
+ Rule('/', endpoint='index'),
393
+ Submount('/blog', [
394
+ Rule('/', endpoint='blog/index'),
395
+ Rule('/entry/<entry_slug>', endpoint='blog/show')
396
+ ])
397
+ ])
398
+
399
+ Now the rule ``'blog/show'`` matches ``/blog/entry/<entry_slug>``.
400
+ """
401
+
402
+ def __init__(self, path, rules):
403
+ self.path = path.rstrip("/")
404
+ self.rules = rules
405
+
406
+ def get_rules(self, map):
407
+ for rulefactory in self.rules:
408
+ for rule in rulefactory.get_rules(map):
409
+ rule = rule.empty()
410
+ rule.rule = self.path + rule.rule
411
+ yield rule
412
+
413
+
414
+ class EndpointPrefix(RuleFactory):
415
+ """Prefixes all endpoints (which must be strings for this factory) with
416
+ another string. This can be useful for sub applications::
417
+
418
+ url_map = Map([
419
+ Rule('/', endpoint='index'),
420
+ EndpointPrefix('blog/', [Submount('/blog', [
421
+ Rule('/', endpoint='index'),
422
+ Rule('/entry/<entry_slug>', endpoint='show')
423
+ ])])
424
+ ])
425
+ """
426
+
427
+ def __init__(self, prefix, rules):
428
+ self.prefix = prefix
429
+ self.rules = rules
430
+
431
+ def get_rules(self, map):
432
+ for rulefactory in self.rules:
433
+ for rule in rulefactory.get_rules(map):
434
+ rule = rule.empty()
435
+ rule.endpoint = self.prefix + rule.endpoint
436
+ yield rule
437
+
438
+
439
+ class RuleTemplate(object):
440
+ """Returns copies of the rules wrapped and expands string templates in
441
+ the endpoint, rule, defaults or subdomain sections.
442
+
443
+ Here a small example for such a rule template::
444
+
445
+ from pythonagent.vendor.werkzeug.routing import Map, Rule, RuleTemplate
446
+
447
+ resource = RuleTemplate([
448
+ Rule('/$name/', endpoint='$name.list'),
449
+ Rule('/$name/<int:id>', endpoint='$name.show')
450
+ ])
451
+
452
+ url_map = Map([resource(name='user'), resource(name='page')])
453
+
454
+ When a rule template is called the keyword arguments are used to
455
+ replace the placeholders in all the string parameters.
456
+ """
457
+
458
+ def __init__(self, rules):
459
+ self.rules = list(rules)
460
+
461
+ def __call__(self, *args, **kwargs):
462
+ return RuleTemplateFactory(self.rules, dict(*args, **kwargs))
463
+
464
+
465
+ class RuleTemplateFactory(RuleFactory):
466
+ """A factory that fills in template variables into rules. Used by
467
+ `RuleTemplate` internally.
468
+
469
+ :internal:
470
+ """
471
+
472
+ def __init__(self, rules, context):
473
+ self.rules = rules
474
+ self.context = context
475
+
476
+ def get_rules(self, map):
477
+ for rulefactory in self.rules:
478
+ for rule in rulefactory.get_rules(map):
479
+ new_defaults = subdomain = None
480
+ if rule.defaults:
481
+ new_defaults = {}
482
+ for key, value in iteritems(rule.defaults):
483
+ if isinstance(value, string_types):
484
+ value = format_string(value, self.context)
485
+ new_defaults[key] = value
486
+ if rule.subdomain is not None:
487
+ subdomain = format_string(rule.subdomain, self.context)
488
+ new_endpoint = rule.endpoint
489
+ if isinstance(new_endpoint, string_types):
490
+ new_endpoint = format_string(new_endpoint, self.context)
491
+ yield Rule(
492
+ format_string(rule.rule, self.context),
493
+ new_defaults,
494
+ subdomain,
495
+ rule.methods,
496
+ rule.build_only,
497
+ new_endpoint,
498
+ rule.strict_slashes,
499
+ )
500
+
501
+
502
+ def _prefix_names(src):
503
+ """ast parse and prefix names with `.` to avoid collision with user vars"""
504
+ tree = ast.parse(src).body[0]
505
+ if isinstance(tree, ast.Expr):
506
+ tree = tree.value
507
+ for node in ast.walk(tree):
508
+ if isinstance(node, ast.Name):
509
+ node.id = "." + node.id
510
+ return tree
511
+
512
+
513
+ _CALL_CONVERTER_CODE_FMT = "self._converters[{elem!r}].to_url()"
514
+ _IF_KWARGS_URL_ENCODE_CODE = """\
515
+ if kwargs:
516
+ q = '?'
517
+ params = self._encode_query_vars(kwargs)
518
+ else:
519
+ q = params = ''
520
+ """
521
+ _IF_KWARGS_URL_ENCODE_AST = _prefix_names(_IF_KWARGS_URL_ENCODE_CODE)
522
+ _URL_ENCODE_AST_NAMES = (_prefix_names("q"), _prefix_names("params"))
523
+
524
+
525
+ @implements_to_string
526
+ class Rule(RuleFactory):
527
+ """A Rule represents one URL pattern. There are some options for `Rule`
528
+ that change the way it behaves and are passed to the `Rule` constructor.
529
+ Note that besides the rule-string all arguments *must* be keyword arguments
530
+ in order to not break the application on Werkzeug upgrades.
531
+
532
+ `string`
533
+ Rule strings basically are just normal URL paths with placeholders in
534
+ the format ``<converter(arguments):name>`` where the converter and the
535
+ arguments are optional. If no converter is defined the `default`
536
+ converter is used which means `string` in the normal configuration.
537
+
538
+ URL rules that end with a slash are branch URLs, others are leaves.
539
+ If you have `strict_slashes` enabled (which is the default), all
540
+ branch URLs that are matched without a trailing slash will trigger a
541
+ redirect to the same URL with the missing slash appended.
542
+
543
+ The converters are defined on the `Map`.
544
+
545
+ `endpoint`
546
+ The endpoint for this rule. This can be anything. A reference to a
547
+ function, a string, a number etc. The preferred way is using a string
548
+ because the endpoint is used for URL generation.
549
+
550
+ `defaults`
551
+ An optional dict with defaults for other rules with the same endpoint.
552
+ This is a bit tricky but useful if you want to have unique URLs::
553
+
554
+ url_map = Map([
555
+ Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
556
+ Rule('/all/page/<int:page>', endpoint='all_entries')
557
+ ])
558
+
559
+ If a user now visits ``http://example.com/all/page/1`` he will be
560
+ redirected to ``http://example.com/all/``. If `redirect_defaults` is
561
+ disabled on the `Map` instance this will only affect the URL
562
+ generation.
563
+
564
+ `subdomain`
565
+ The subdomain rule string for this rule. If not specified the rule
566
+ only matches for the `default_subdomain` of the map. If the map is
567
+ not bound to a subdomain this feature is disabled.
568
+
569
+ Can be useful if you want to have user profiles on different subdomains
570
+ and all subdomains are forwarded to your application::
571
+
572
+ url_map = Map([
573
+ Rule('/', subdomain='<username>', endpoint='user/homepage'),
574
+ Rule('/stats', subdomain='<username>', endpoint='user/stats')
575
+ ])
576
+
577
+ `methods`
578
+ A sequence of http methods this rule applies to. If not specified, all
579
+ methods are allowed. For example this can be useful if you want different
580
+ endpoints for `POST` and `GET`. If methods are defined and the path
581
+ matches but the method matched against is not in this list or in the
582
+ list of another rule for that path the error raised is of the type
583
+ `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the
584
+ list of methods and `HEAD` is not, `HEAD` is added automatically.
585
+
586
+ `strict_slashes`
587
+ Override the `Map` setting for `strict_slashes` only for this rule. If
588
+ not specified the `Map` setting is used.
589
+
590
+ `merge_slashes`
591
+ Override :attr:`Map.merge_slashes` for this rule.
592
+
593
+ `build_only`
594
+ Set this to True and the rule will never match but will create a URL
595
+ that can be build. This is useful if you have resources on a subdomain
596
+ or folder that are not handled by the WSGI application (like static data)
597
+
598
+ `redirect_to`
599
+ If given this must be either a string or callable. In case of a
600
+ callable it's called with the url adapter that triggered the match and
601
+ the values of the URL as keyword arguments and has to return the target
602
+ for the redirect, otherwise it has to be a string with placeholders in
603
+ rule syntax::
604
+
605
+ def foo_with_slug(adapter, id):
606
+ # ask the database for the slug for the old id. this of
607
+ # course has nothing to do with werkzeug.
608
+ return 'foo/' + Foo.get_slug_for_id(id)
609
+
610
+ url_map = Map([
611
+ Rule('/foo/<slug>', endpoint='foo'),
612
+ Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
613
+ Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
614
+ ])
615
+
616
+ When the rule is matched the routing system will raise a
617
+ `RequestRedirect` exception with the target for the redirect.
618
+
619
+ Keep in mind that the URL will be joined against the URL root of the
620
+ script so don't use a leading slash on the target URL unless you
621
+ really mean root of that domain.
622
+
623
+ `alias`
624
+ If enabled this rule serves as an alias for another rule with the same
625
+ endpoint and arguments.
626
+
627
+ `host`
628
+ If provided and the URL map has host matching enabled this can be
629
+ used to provide a match rule for the whole host. This also means
630
+ that the subdomain feature is disabled.
631
+
632
+ `websocket`
633
+ If ``True``, this rule is only matches for WebSocket (``ws://``,
634
+ ``wss://``) requests. By default, rules will only match for HTTP
635
+ requests.
636
+
637
+ .. versionadded:: 1.0
638
+ Added ``websocket``.
639
+
640
+ .. versionadded:: 1.0
641
+ Added ``merge_slashes``.
642
+
643
+ .. versionadded:: 0.7
644
+ Added ``alias`` and ``host``.
645
+
646
+ .. versionchanged:: 0.6.1
647
+ ``HEAD`` is added to ``methods`` if ``GET`` is present.
648
+ """
649
+
650
+ def __init__(
651
+ self,
652
+ string,
653
+ defaults=None,
654
+ subdomain=None,
655
+ methods=None,
656
+ build_only=False,
657
+ endpoint=None,
658
+ strict_slashes=None,
659
+ merge_slashes=None,
660
+ redirect_to=None,
661
+ alias=False,
662
+ host=None,
663
+ websocket=False,
664
+ ):
665
+ if not string.startswith("/"):
666
+ raise ValueError("urls must start with a leading slash")
667
+ self.rule = string
668
+ self.is_leaf = not string.endswith("/")
669
+
670
+ self.map = None
671
+ self.strict_slashes = strict_slashes
672
+ self.merge_slashes = merge_slashes
673
+ self.subdomain = subdomain
674
+ self.host = host
675
+ self.defaults = defaults
676
+ self.build_only = build_only
677
+ self.alias = alias
678
+ self.websocket = websocket
679
+
680
+ if methods is not None:
681
+ if isinstance(methods, str):
682
+ raise TypeError("'methods' should be a list of strings.")
683
+
684
+ methods = {x.upper() for x in methods}
685
+
686
+ if "HEAD" not in methods and "GET" in methods:
687
+ methods.add("HEAD")
688
+
689
+ if websocket and methods - {"GET", "HEAD", "OPTIONS"}:
690
+ raise ValueError(
691
+ "WebSocket rules can only use 'GET', 'HEAD', and 'OPTIONS' methods."
692
+ )
693
+
694
+ self.methods = methods
695
+ self.endpoint = endpoint
696
+ self.redirect_to = redirect_to
697
+
698
+ if defaults:
699
+ self.arguments = set(map(str, defaults))
700
+ else:
701
+ self.arguments = set()
702
+ self._trace = self._converters = self._regex = self._argument_weights = None
703
+
704
+ def empty(self):
705
+ """
706
+ Return an unbound copy of this rule.
707
+
708
+ This can be useful if want to reuse an already bound URL for another
709
+ map. See ``get_empty_kwargs`` to override what keyword arguments are
710
+ provided to the new copy.
711
+ """
712
+ return type(self)(self.rule, **self.get_empty_kwargs())
713
+
714
+ def get_empty_kwargs(self):
715
+ """
716
+ Provides kwargs for instantiating empty copy with empty()
717
+
718
+ Use this method to provide custom keyword arguments to the subclass of
719
+ ``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
720
+ has custom keyword arguments that are needed at instantiation.
721
+
722
+ Must return a ``dict`` that will be provided as kwargs to the new
723
+ instance of ``Rule``, following the initial ``self.rule`` value which
724
+ is always provided as the first, required positional argument.
725
+ """
726
+ defaults = None
727
+ if self.defaults:
728
+ defaults = dict(self.defaults)
729
+ return dict(
730
+ defaults=defaults,
731
+ subdomain=self.subdomain,
732
+ methods=self.methods,
733
+ build_only=self.build_only,
734
+ endpoint=self.endpoint,
735
+ strict_slashes=self.strict_slashes,
736
+ redirect_to=self.redirect_to,
737
+ alias=self.alias,
738
+ host=self.host,
739
+ )
740
+
741
+ def get_rules(self, map):
742
+ yield self
743
+
744
+ def refresh(self):
745
+ """Rebinds and refreshes the URL. Call this if you modified the
746
+ rule in place.
747
+
748
+ :internal:
749
+ """
750
+ self.bind(self.map, rebind=True)
751
+
752
+ def bind(self, map, rebind=False):
753
+ """Bind the url to a map and create a regular expression based on
754
+ the information from the rule itself and the defaults from the map.
755
+
756
+ :internal:
757
+ """
758
+ if self.map is not None and not rebind:
759
+ raise RuntimeError("url rule %r already bound to map %r" % (self, self.map))
760
+ self.map = map
761
+ if self.strict_slashes is None:
762
+ self.strict_slashes = map.strict_slashes
763
+ if self.merge_slashes is None:
764
+ self.merge_slashes = map.merge_slashes
765
+ if self.subdomain is None:
766
+ self.subdomain = map.default_subdomain
767
+ self.compile()
768
+
769
+ def get_converter(self, variable_name, converter_name, args, kwargs):
770
+ """Looks up the converter for the given parameter.
771
+
772
+ .. versionadded:: 0.9
773
+ """
774
+ if converter_name not in self.map.converters:
775
+ raise LookupError("the converter %r does not exist" % converter_name)
776
+ return self.map.converters[converter_name](self.map, *args, **kwargs)
777
+
778
+ def _encode_query_vars(self, query_vars):
779
+ return url_encode(
780
+ query_vars,
781
+ charset=self.map.charset,
782
+ sort=self.map.sort_parameters,
783
+ key=self.map.sort_key,
784
+ )
785
+
786
+ def compile(self):
787
+ """Compiles the regular expression and stores it."""
788
+ assert self.map is not None, "rule not bound"
789
+
790
+ if self.map.host_matching:
791
+ domain_rule = self.host or ""
792
+ else:
793
+ domain_rule = self.subdomain or ""
794
+
795
+ self._trace = []
796
+ self._converters = {}
797
+ self._static_weights = []
798
+ self._argument_weights = []
799
+ regex_parts = []
800
+
801
+ def _build_regex(rule):
802
+ index = 0
803
+ for converter, arguments, variable in parse_rule(rule):
804
+ if converter is None:
805
+ for match in re.finditer(r"/+|[^/]+", variable):
806
+ part = match.group(0)
807
+ if part.startswith("/"):
808
+ if self.merge_slashes:
809
+ regex_parts.append(r"/+?")
810
+ self._trace.append((False, "/"))
811
+ else:
812
+ regex_parts.append(part)
813
+ self._trace.append((False, part))
814
+ continue
815
+ self._trace.append((False, part))
816
+ regex_parts.append(re.escape(part))
817
+ if part:
818
+ self._static_weights.append((index, -len(part)))
819
+ else:
820
+ if arguments:
821
+ c_args, c_kwargs = parse_converter_args(arguments)
822
+ else:
823
+ c_args = ()
824
+ c_kwargs = {}
825
+ convobj = self.get_converter(variable, converter, c_args, c_kwargs)
826
+ regex_parts.append("(?P<%s>%s)" % (variable, convobj.regex))
827
+ self._converters[variable] = convobj
828
+ self._trace.append((True, variable))
829
+ self._argument_weights.append(convobj.weight)
830
+ self.arguments.add(str(variable))
831
+ index = index + 1
832
+
833
+ _build_regex(domain_rule)
834
+ regex_parts.append("\\|")
835
+ self._trace.append((False, "|"))
836
+ _build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
837
+ if not self.is_leaf:
838
+ self._trace.append((False, "/"))
839
+
840
+ self._build = self._compile_builder(False).__get__(self, None)
841
+ self._build_unknown = self._compile_builder(True).__get__(self, None)
842
+
843
+ if self.build_only:
844
+ return
845
+
846
+ if not (self.is_leaf and self.strict_slashes):
847
+ reps = u"*" if self.merge_slashes else u"?"
848
+ tail = u"(?<!/)(?P<__suffix__>/%s)" % reps
849
+ else:
850
+ tail = u""
851
+
852
+ regex = u"^%s%s$" % (u"".join(regex_parts), tail)
853
+ self._regex = re.compile(regex, re.UNICODE)
854
+
855
+ def match(self, path, method=None):
856
+ """Check if the rule matches a given path. Path is a string in the
857
+ form ``"subdomain|/path"`` and is assembled by the map. If
858
+ the map is doing host matching the subdomain part will be the host
859
+ instead.
860
+
861
+ If the rule matches a dict with the converted values is returned,
862
+ otherwise the return value is `None`.
863
+
864
+ :internal:
865
+ """
866
+ if not self.build_only:
867
+ require_redirect = False
868
+
869
+ m = self._regex.search(path)
870
+ if m is not None:
871
+ groups = m.groupdict()
872
+ # we have a folder like part of the url without a trailing
873
+ # slash and strict slashes enabled. raise an exception that
874
+ # tells the map to redirect to the same url but with a
875
+ # trailing slash
876
+ if (
877
+ self.strict_slashes
878
+ and not self.is_leaf
879
+ and not groups.pop("__suffix__")
880
+ and (
881
+ method is None or self.methods is None or method in self.methods
882
+ )
883
+ ):
884
+ path += "/"
885
+ require_redirect = True
886
+ # if we are not in strict slashes mode we have to remove
887
+ # a __suffix__
888
+ elif not self.strict_slashes:
889
+ del groups["__suffix__"]
890
+
891
+ result = {}
892
+ for name, value in iteritems(groups):
893
+ try:
894
+ value = self._converters[name].to_python(value)
895
+ except ValidationError:
896
+ return
897
+ result[str(name)] = value
898
+ if self.defaults:
899
+ result.update(self.defaults)
900
+
901
+ if self.merge_slashes:
902
+ new_path = "|".join(self.build(result, False))
903
+ if path.endswith("/") and not new_path.endswith("/"):
904
+ new_path += "/"
905
+ if new_path.count("/") < path.count("/"):
906
+ path = new_path
907
+ require_redirect = True
908
+
909
+ if require_redirect:
910
+ path = path.split("|", 1)[1]
911
+ raise RequestPath(path)
912
+
913
+ if self.alias and self.map.redirect_defaults:
914
+ raise RequestAliasRedirect(result)
915
+
916
+ return result
917
+
918
+ @staticmethod
919
+ def _get_func_code(code, name):
920
+ globs, locs = {}, {}
921
+ exec(code, globs, locs)
922
+ return locs[name]
923
+
924
+ def _compile_builder(self, append_unknown=True):
925
+ defaults = self.defaults or {}
926
+ dom_ops = []
927
+ url_ops = []
928
+
929
+ opl = dom_ops
930
+ for is_dynamic, data in self._trace:
931
+ if data == "|" and opl is dom_ops:
932
+ opl = url_ops
933
+ continue
934
+ # this seems like a silly case to ever come up but:
935
+ # if a default is given for a value that appears in the rule,
936
+ # resolve it to a constant ahead of time
937
+ if is_dynamic and data in defaults:
938
+ data = self._converters[data].to_url(defaults[data])
939
+ opl.append((False, data))
940
+ elif not is_dynamic:
941
+ opl.append(
942
+ (False, url_quote(to_bytes(data, self.map.charset), safe="/:|+"))
943
+ )
944
+ else:
945
+ opl.append((True, data))
946
+
947
+ def _convert(elem):
948
+ ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem))
949
+ ret.args = [ast.Name(str(elem), ast.Load())] # str for py2
950
+ return ret
951
+
952
+ def _parts(ops):
953
+ parts = [
954
+ _convert(elem) if is_dynamic else ast.Str(s=elem)
955
+ for is_dynamic, elem in ops
956
+ ]
957
+ parts = parts or [ast.Str("")]
958
+ # constant fold
959
+ ret = [parts[0]]
960
+ for p in parts[1:]:
961
+ if isinstance(p, ast.Str) and isinstance(ret[-1], ast.Str):
962
+ ret[-1] = ast.Str(ret[-1].s + p.s)
963
+ else:
964
+ ret.append(p)
965
+ return ret
966
+
967
+ dom_parts = _parts(dom_ops)
968
+ url_parts = _parts(url_ops)
969
+ if not append_unknown:
970
+ body = []
971
+ else:
972
+ body = [_IF_KWARGS_URL_ENCODE_AST]
973
+ url_parts.extend(_URL_ENCODE_AST_NAMES)
974
+
975
+ def _join(parts):
976
+ if len(parts) == 1: # shortcut
977
+ return parts[0]
978
+ elif hasattr(ast, "JoinedStr"): # py36+
979
+ return ast.JoinedStr(parts)
980
+ else:
981
+ call = _prefix_names('"".join()')
982
+ call.args = [ast.Tuple(parts, ast.Load())]
983
+ return call
984
+
985
+ body.append(
986
+ ast.Return(ast.Tuple([_join(dom_parts), _join(url_parts)], ast.Load()))
987
+ )
988
+
989
+ # str is necessary for python2
990
+ pargs = [
991
+ str(elem)
992
+ for is_dynamic, elem in dom_ops + url_ops
993
+ if is_dynamic and elem not in defaults
994
+ ]
995
+ kargs = [str(k) for k in defaults]
996
+
997
+ func_ast = _prefix_names("def _(): pass")
998
+ func_ast.name = "<builder:{!r}>".format(self.rule)
999
+ if hasattr(ast, "arg"): # py3
1000
+ func_ast.args.args.append(ast.arg(".self", None))
1001
+ for arg in pargs + kargs:
1002
+ func_ast.args.args.append(ast.arg(arg, None))
1003
+ func_ast.args.kwarg = ast.arg(".kwargs", None)
1004
+ else:
1005
+ func_ast.args.args.append(ast.Name(".self", ast.Param()))
1006
+ for arg in pargs + kargs:
1007
+ func_ast.args.args.append(ast.Name(arg, ast.Param()))
1008
+ func_ast.args.kwarg = ".kwargs"
1009
+ for _ in kargs:
1010
+ func_ast.args.defaults.append(ast.Str(""))
1011
+ func_ast.body = body
1012
+
1013
+ # use `ast.parse` instead of `ast.Module` for better portability
1014
+ # python3.8 changes the signature of `ast.Module`
1015
+ module = ast.parse("")
1016
+ module.body = [func_ast]
1017
+
1018
+ # mark everything as on line 1, offset 0
1019
+ # less error-prone than `ast.fix_missing_locations`
1020
+ # bad line numbers cause an assert to fail in debug builds
1021
+ for node in ast.walk(module):
1022
+ if "lineno" in node._attributes:
1023
+ node.lineno = 1
1024
+ if "col_offset" in node._attributes:
1025
+ node.col_offset = 0
1026
+
1027
+ code = compile(module, "<werkzeug routing>", "exec")
1028
+ return self._get_func_code(code, func_ast.name)
1029
+
1030
+ def build(self, values, append_unknown=True):
1031
+ """Assembles the relative url for that rule and the subdomain.
1032
+ If building doesn't work for some reasons `None` is returned.
1033
+
1034
+ :internal:
1035
+ """
1036
+ try:
1037
+ if append_unknown:
1038
+ return self._build_unknown(**values)
1039
+ else:
1040
+ return self._build(**values)
1041
+ except ValidationError:
1042
+ return None
1043
+
1044
+ def provides_defaults_for(self, rule):
1045
+ """Check if this rule has defaults for a given rule.
1046
+
1047
+ :internal:
1048
+ """
1049
+ return (
1050
+ not self.build_only
1051
+ and self.defaults
1052
+ and self.endpoint == rule.endpoint
1053
+ and self != rule
1054
+ and self.arguments == rule.arguments
1055
+ )
1056
+
1057
+ def suitable_for(self, values, method=None):
1058
+ """Check if the dict of values has enough data for url generation.
1059
+
1060
+ :internal:
1061
+ """
1062
+ # if a method was given explicitly and that method is not supported
1063
+ # by this rule, this rule is not suitable.
1064
+ if (
1065
+ method is not None
1066
+ and self.methods is not None
1067
+ and method not in self.methods
1068
+ ):
1069
+ return False
1070
+
1071
+ defaults = self.defaults or ()
1072
+
1073
+ # all arguments required must be either in the defaults dict or
1074
+ # the value dictionary otherwise it's not suitable
1075
+ for key in self.arguments:
1076
+ if key not in defaults and key not in values:
1077
+ return False
1078
+
1079
+ # in case defaults are given we ensure that either the value was
1080
+ # skipped or the value is the same as the default value.
1081
+ if defaults:
1082
+ for key, value in iteritems(defaults):
1083
+ if key in values and value != values[key]:
1084
+ return False
1085
+
1086
+ return True
1087
+
1088
+ def match_compare_key(self):
1089
+ """The match compare key for sorting.
1090
+
1091
+ Current implementation:
1092
+
1093
+ 1. rules without any arguments come first for performance
1094
+ reasons only as we expect them to match faster and some
1095
+ common ones usually don't have any arguments (index pages etc.)
1096
+ 2. rules with more static parts come first so the second argument
1097
+ is the negative length of the number of the static weights.
1098
+ 3. we order by static weights, which is a combination of index
1099
+ and length
1100
+ 4. The more complex rules come first so the next argument is the
1101
+ negative length of the number of argument weights.
1102
+ 5. lastly we order by the actual argument weights.
1103
+
1104
+ :internal:
1105
+ """
1106
+ return (
1107
+ bool(self.arguments),
1108
+ -len(self._static_weights),
1109
+ self._static_weights,
1110
+ -len(self._argument_weights),
1111
+ self._argument_weights,
1112
+ )
1113
+
1114
+ def build_compare_key(self):
1115
+ """The build compare key for sorting.
1116
+
1117
+ :internal:
1118
+ """
1119
+ return 1 if self.alias else 0, -len(self.arguments), -len(self.defaults or ())
1120
+
1121
+ def __eq__(self, other):
1122
+ return self.__class__ is other.__class__ and self._trace == other._trace
1123
+
1124
+ __hash__ = None
1125
+
1126
+ def __ne__(self, other):
1127
+ return not self.__eq__(other)
1128
+
1129
+ def __str__(self):
1130
+ return self.rule
1131
+
1132
+ @native_string_result
1133
+ def __repr__(self):
1134
+ if self.map is None:
1135
+ return u"<%s (unbound)>" % self.__class__.__name__
1136
+ tmp = []
1137
+ for is_dynamic, data in self._trace:
1138
+ if is_dynamic:
1139
+ tmp.append(u"<%s>" % data)
1140
+ else:
1141
+ tmp.append(data)
1142
+ return u"<%s %s%s -> %s>" % (
1143
+ self.__class__.__name__,
1144
+ repr((u"".join(tmp)).lstrip(u"|")).lstrip(u"u"),
1145
+ self.methods is not None and u" (%s)" % u", ".join(self.methods) or u"",
1146
+ self.endpoint,
1147
+ )
1148
+
1149
+
1150
+ class BaseConverter(object):
1151
+ """Base class for all converters."""
1152
+
1153
+ regex = "[^/]+"
1154
+ weight = 100
1155
+
1156
+ def __init__(self, map):
1157
+ self.map = map
1158
+
1159
+ def to_python(self, value):
1160
+ return value
1161
+
1162
+ def to_url(self, value):
1163
+ if isinstance(value, (bytes, bytearray)):
1164
+ return _fast_url_quote(value)
1165
+ return _fast_url_quote(text_type(value).encode(self.map.charset))
1166
+
1167
+
1168
+ class UnicodeConverter(BaseConverter):
1169
+ """This converter is the default converter and accepts any string but
1170
+ only one path segment. Thus the string can not include a slash.
1171
+
1172
+ This is the default validator.
1173
+
1174
+ Example::
1175
+
1176
+ Rule('/pages/<page>'),
1177
+ Rule('/<string(length=2):lang_code>')
1178
+
1179
+ :param map: the :class:`Map`.
1180
+ :param minlength: the minimum length of the string. Must be greater
1181
+ or equal 1.
1182
+ :param maxlength: the maximum length of the string.
1183
+ :param length: the exact length of the string.
1184
+ """
1185
+
1186
+ def __init__(self, map, minlength=1, maxlength=None, length=None):
1187
+ BaseConverter.__init__(self, map)
1188
+ if length is not None:
1189
+ length = "{%d}" % int(length)
1190
+ else:
1191
+ if maxlength is None:
1192
+ maxlength = ""
1193
+ else:
1194
+ maxlength = int(maxlength)
1195
+ length = "{%s,%s}" % (int(minlength), maxlength)
1196
+ self.regex = "[^/]" + length
1197
+
1198
+
1199
+ class AnyConverter(BaseConverter):
1200
+ """Matches one of the items provided. Items can either be Python
1201
+ identifiers or strings::
1202
+
1203
+ Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
1204
+
1205
+ :param map: the :class:`Map`.
1206
+ :param items: this function accepts the possible items as positional
1207
+ arguments.
1208
+ """
1209
+
1210
+ def __init__(self, map, *items):
1211
+ BaseConverter.__init__(self, map)
1212
+ self.regex = "(?:%s)" % "|".join([re.escape(x) for x in items])
1213
+
1214
+
1215
+ class PathConverter(BaseConverter):
1216
+ """Like the default :class:`UnicodeConverter`, but it also matches
1217
+ slashes. This is useful for wikis and similar applications::
1218
+
1219
+ Rule('/<path:wikipage>')
1220
+ Rule('/<path:wikipage>/edit')
1221
+
1222
+ :param map: the :class:`Map`.
1223
+ """
1224
+
1225
+ regex = "[^/].*?"
1226
+ weight = 200
1227
+
1228
+
1229
+ class NumberConverter(BaseConverter):
1230
+ """Baseclass for `IntegerConverter` and `FloatConverter`.
1231
+
1232
+ :internal:
1233
+ """
1234
+
1235
+ weight = 50
1236
+
1237
+ def __init__(self, map, fixed_digits=0, min=None, max=None, signed=False):
1238
+ if signed:
1239
+ self.regex = self.signed_regex
1240
+ BaseConverter.__init__(self, map)
1241
+ self.fixed_digits = fixed_digits
1242
+ self.min = min
1243
+ self.max = max
1244
+ self.signed = signed
1245
+
1246
+ def to_python(self, value):
1247
+ if self.fixed_digits and len(value) != self.fixed_digits:
1248
+ raise ValidationError()
1249
+ value = self.num_convert(value)
1250
+ if (self.min is not None and value < self.min) or (
1251
+ self.max is not None and value > self.max
1252
+ ):
1253
+ raise ValidationError()
1254
+ return value
1255
+
1256
+ def to_url(self, value):
1257
+ value = self.num_convert(value)
1258
+ if self.fixed_digits:
1259
+ value = ("%%0%sd" % self.fixed_digits) % value
1260
+ return str(value)
1261
+
1262
+ @property
1263
+ def signed_regex(self):
1264
+ return r"-?" + self.regex
1265
+
1266
+
1267
+ class IntegerConverter(NumberConverter):
1268
+ """This converter only accepts integer values::
1269
+
1270
+ Rule("/page/<int:page>")
1271
+
1272
+ By default it only accepts unsigned, positive values. The ``signed``
1273
+ parameter will enable signed, negative values. ::
1274
+
1275
+ Rule("/page/<int(signed=True):page>")
1276
+
1277
+ :param map: The :class:`Map`.
1278
+ :param fixed_digits: The number of fixed digits in the URL. If you
1279
+ set this to ``4`` for example, the rule will only match if the
1280
+ URL looks like ``/0001/``. The default is variable length.
1281
+ :param min: The minimal value.
1282
+ :param max: The maximal value.
1283
+ :param signed: Allow signed (negative) values.
1284
+
1285
+ .. versionadded:: 0.15
1286
+ The ``signed`` parameter.
1287
+ """
1288
+
1289
+ regex = r"\d+"
1290
+ num_convert = int
1291
+
1292
+
1293
+ class FloatConverter(NumberConverter):
1294
+ """This converter only accepts floating point values::
1295
+
1296
+ Rule("/probability/<float:probability>")
1297
+
1298
+ By default it only accepts unsigned, positive values. The ``signed``
1299
+ parameter will enable signed, negative values. ::
1300
+
1301
+ Rule("/offset/<float(signed=True):offset>")
1302
+
1303
+ :param map: The :class:`Map`.
1304
+ :param min: The minimal value.
1305
+ :param max: The maximal value.
1306
+ :param signed: Allow signed (negative) values.
1307
+
1308
+ .. versionadded:: 0.15
1309
+ The ``signed`` parameter.
1310
+ """
1311
+
1312
+ regex = r"\d+\.\d+"
1313
+ num_convert = float
1314
+
1315
+ def __init__(self, map, min=None, max=None, signed=False):
1316
+ NumberConverter.__init__(self, map, min=min, max=max, signed=signed)
1317
+
1318
+
1319
+ class UUIDConverter(BaseConverter):
1320
+ """This converter only accepts UUID strings::
1321
+
1322
+ Rule('/object/<uuid:identifier>')
1323
+
1324
+ .. versionadded:: 0.10
1325
+
1326
+ :param map: the :class:`Map`.
1327
+ """
1328
+
1329
+ regex = (
1330
+ r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-"
1331
+ r"[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
1332
+ )
1333
+
1334
+ def to_python(self, value):
1335
+ return uuid.UUID(value)
1336
+
1337
+ def to_url(self, value):
1338
+ return str(value)
1339
+
1340
+
1341
+ #: the default converter mapping for the map.
1342
+ DEFAULT_CONVERTERS = {
1343
+ "default": UnicodeConverter,
1344
+ "string": UnicodeConverter,
1345
+ "any": AnyConverter,
1346
+ "path": PathConverter,
1347
+ "int": IntegerConverter,
1348
+ "float": FloatConverter,
1349
+ "uuid": UUIDConverter,
1350
+ }
1351
+
1352
+
1353
+ class Map(object):
1354
+ """The map class stores all the URL rules and some configuration
1355
+ parameters. Some of the configuration values are only stored on the
1356
+ `Map` instance since those affect all rules, others are just defaults
1357
+ and can be overridden for each rule. Note that you have to specify all
1358
+ arguments besides the `rules` as keyword arguments!
1359
+
1360
+ :param rules: sequence of url rules for this map.
1361
+ :param default_subdomain: The default subdomain for rules without a
1362
+ subdomain defined.
1363
+ :param charset: charset of the url. defaults to ``"utf-8"``
1364
+ :param strict_slashes: If a rule ends with a slash but the matched
1365
+ URL does not, redirect to the URL with a trailing slash.
1366
+ :param merge_slashes: Merge consecutive slashes when matching or
1367
+ building URLs. Matches will redirect to the normalized URL.
1368
+ Slashes in variable parts are not merged.
1369
+ :param redirect_defaults: This will redirect to the default rule if it
1370
+ wasn't visited that way. This helps creating
1371
+ unique URLs.
1372
+ :param converters: A dict of converters that adds additional converters
1373
+ to the list of converters. If you redefine one
1374
+ converter this will override the original one.
1375
+ :param sort_parameters: If set to `True` the url parameters are sorted.
1376
+ See `url_encode` for more details.
1377
+ :param sort_key: The sort key function for `url_encode`.
1378
+ :param encoding_errors: the error method to use for decoding
1379
+ :param host_matching: if set to `True` it enables the host matching
1380
+ feature and disables the subdomain one. If
1381
+ enabled the `host` parameter to rules is used
1382
+ instead of the `subdomain` one.
1383
+
1384
+ .. versionchanged:: 1.0
1385
+ If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
1386
+ will match.
1387
+
1388
+ .. versionchanged:: 1.0
1389
+ Added ``merge_slashes``.
1390
+
1391
+ .. versionchanged:: 0.7
1392
+ Added ``encoding_errors`` and ``host_matching``.
1393
+
1394
+ .. versionchanged:: 0.5
1395
+ Added ``sort_parameters`` and ``sort_key``.
1396
+ """
1397
+
1398
+ #: A dict of default converters to be used.
1399
+ default_converters = ImmutableDict(DEFAULT_CONVERTERS)
1400
+
1401
+ #: The type of lock to use when updating.
1402
+ #:
1403
+ #: .. versionadded:: 1.0
1404
+ lock_class = Lock
1405
+
1406
+ def __init__(
1407
+ self,
1408
+ rules=None,
1409
+ default_subdomain="",
1410
+ charset="utf-8",
1411
+ strict_slashes=True,
1412
+ merge_slashes=True,
1413
+ redirect_defaults=True,
1414
+ converters=None,
1415
+ sort_parameters=False,
1416
+ sort_key=None,
1417
+ encoding_errors="replace",
1418
+ host_matching=False,
1419
+ ):
1420
+ self._rules = []
1421
+ self._rules_by_endpoint = {}
1422
+ self._remap = True
1423
+ self._remap_lock = self.lock_class()
1424
+
1425
+ self.default_subdomain = default_subdomain
1426
+ self.charset = charset
1427
+ self.encoding_errors = encoding_errors
1428
+ self.strict_slashes = strict_slashes
1429
+ self.merge_slashes = merge_slashes
1430
+ self.redirect_defaults = redirect_defaults
1431
+ self.host_matching = host_matching
1432
+
1433
+ self.converters = self.default_converters.copy()
1434
+ if converters:
1435
+ self.converters.update(converters)
1436
+
1437
+ self.sort_parameters = sort_parameters
1438
+ self.sort_key = sort_key
1439
+
1440
+ for rulefactory in rules or ():
1441
+ self.add(rulefactory)
1442
+
1443
+ def is_endpoint_expecting(self, endpoint, *arguments):
1444
+ """Iterate over all rules and check if the endpoint expects
1445
+ the arguments provided. This is for example useful if you have
1446
+ some URLs that expect a language code and others that do not and
1447
+ you want to wrap the builder a bit so that the current language
1448
+ code is automatically added if not provided but endpoints expect
1449
+ it.
1450
+
1451
+ :param endpoint: the endpoint to check.
1452
+ :param arguments: this function accepts one or more arguments
1453
+ as positional arguments. Each one of them is
1454
+ checked.
1455
+ """
1456
+ self.update()
1457
+ arguments = set(arguments)
1458
+ for rule in self._rules_by_endpoint[endpoint]:
1459
+ if arguments.issubset(rule.arguments):
1460
+ return True
1461
+ return False
1462
+
1463
+ def iter_rules(self, endpoint=None):
1464
+ """Iterate over all rules or the rules of an endpoint.
1465
+
1466
+ :param endpoint: if provided only the rules for that endpoint
1467
+ are returned.
1468
+ :return: an iterator
1469
+ """
1470
+ self.update()
1471
+ if endpoint is not None:
1472
+ return iter(self._rules_by_endpoint[endpoint])
1473
+ return iter(self._rules)
1474
+
1475
+ def add(self, rulefactory):
1476
+ """Add a new rule or factory to the map and bind it. Requires that the
1477
+ rule is not bound to another map.
1478
+
1479
+ :param rulefactory: a :class:`Rule` or :class:`RuleFactory`
1480
+ """
1481
+ for rule in rulefactory.get_rules(self):
1482
+ rule.bind(self)
1483
+ self._rules.append(rule)
1484
+ self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule)
1485
+ self._remap = True
1486
+
1487
+ def bind(
1488
+ self,
1489
+ server_name,
1490
+ script_name=None,
1491
+ subdomain=None,
1492
+ url_scheme="http",
1493
+ default_method="GET",
1494
+ path_info=None,
1495
+ query_args=None,
1496
+ ):
1497
+ """Return a new :class:`MapAdapter` with the details specified to the
1498
+ call. Note that `script_name` will default to ``'/'`` if not further
1499
+ specified or `None`. The `server_name` at least is a requirement
1500
+ because the HTTP RFC requires absolute URLs for redirects and so all
1501
+ redirect exceptions raised by Werkzeug will contain the full canonical
1502
+ URL.
1503
+
1504
+ If no path_info is passed to :meth:`match` it will use the default path
1505
+ info passed to bind. While this doesn't really make sense for
1506
+ manual bind calls, it's useful if you bind a map to a WSGI
1507
+ environment which already contains the path info.
1508
+
1509
+ `subdomain` will default to the `default_subdomain` for this map if
1510
+ no defined. If there is no `default_subdomain` you cannot use the
1511
+ subdomain feature.
1512
+
1513
+ .. versionchanged:: 1.0
1514
+ If ``url_scheme`` is ``ws`` or ``wss``, only WebSocket rules
1515
+ will match.
1516
+
1517
+ .. versionchanged:: 0.15
1518
+ ``path_info`` defaults to ``'/'`` if ``None``.
1519
+
1520
+ .. versionchanged:: 0.8
1521
+ ``query_args`` can be a string.
1522
+
1523
+ .. versionchanged:: 0.7
1524
+ Added ``query_args``.
1525
+ """
1526
+ server_name = server_name.lower()
1527
+ if self.host_matching:
1528
+ if subdomain is not None:
1529
+ raise RuntimeError("host matching enabled and a subdomain was provided")
1530
+ elif subdomain is None:
1531
+ subdomain = self.default_subdomain
1532
+ if script_name is None:
1533
+ script_name = "/"
1534
+ if path_info is None:
1535
+ path_info = "/"
1536
+ try:
1537
+ server_name = _encode_idna(server_name)
1538
+ except UnicodeError:
1539
+ raise BadHost()
1540
+ return MapAdapter(
1541
+ self,
1542
+ server_name,
1543
+ script_name,
1544
+ subdomain,
1545
+ url_scheme,
1546
+ path_info,
1547
+ default_method,
1548
+ query_args,
1549
+ )
1550
+
1551
+ def bind_to_environ(self, environ, server_name=None, subdomain=None):
1552
+ """Like :meth:`bind` but you can pass it an WSGI environment and it
1553
+ will fetch the information from that dictionary. Note that because of
1554
+ limitations in the protocol there is no way to get the current
1555
+ subdomain and real `server_name` from the environment. If you don't
1556
+ provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or
1557
+ `HTTP_HOST` if provided) as used `server_name` with disabled subdomain
1558
+ feature.
1559
+
1560
+ If `subdomain` is `None` but an environment and a server name is
1561
+ provided it will calculate the current subdomain automatically.
1562
+ Example: `server_name` is ``'example.com'`` and the `SERVER_NAME`
1563
+ in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated
1564
+ subdomain will be ``'staging.dev'``.
1565
+
1566
+ If the object passed as environ has an environ attribute, the value of
1567
+ this attribute is used instead. This allows you to pass request
1568
+ objects. Additionally `PATH_INFO` added as a default of the
1569
+ :class:`MapAdapter` so that you don't have to pass the path info to
1570
+ the match method.
1571
+
1572
+ .. versionchanged:: 1.0.0
1573
+ If the passed server name specifies port 443, it will match
1574
+ if the incoming scheme is ``https`` without a port.
1575
+
1576
+ .. versionchanged:: 1.0.0
1577
+ A warning is shown when the passed server name does not
1578
+ match the incoming WSGI server name.
1579
+
1580
+ .. versionchanged:: 0.8
1581
+ This will no longer raise a ValueError when an unexpected server
1582
+ name was passed.
1583
+
1584
+ .. versionchanged:: 0.5
1585
+ previously this method accepted a bogus `calculate_subdomain`
1586
+ parameter that did not have any effect. It was removed because
1587
+ of that.
1588
+
1589
+ :param environ: a WSGI environment.
1590
+ :param server_name: an optional server name hint (see above).
1591
+ :param subdomain: optionally the current subdomain (see above).
1592
+ """
1593
+ environ = _get_environ(environ)
1594
+ wsgi_server_name = get_host(environ).lower()
1595
+ scheme = environ["wsgi.url_scheme"]
1596
+
1597
+ if server_name is None:
1598
+ server_name = wsgi_server_name
1599
+ else:
1600
+ server_name = server_name.lower()
1601
+
1602
+ # strip standard port to match get_host()
1603
+ if scheme == "http" and server_name.endswith(":80"):
1604
+ server_name = server_name[:-3]
1605
+ elif scheme == "https" and server_name.endswith(":443"):
1606
+ server_name = server_name[:-4]
1607
+
1608
+ if subdomain is None and not self.host_matching:
1609
+ cur_server_name = wsgi_server_name.split(".")
1610
+ real_server_name = server_name.split(".")
1611
+ offset = -len(real_server_name)
1612
+
1613
+ if cur_server_name[offset:] != real_server_name:
1614
+ # This can happen even with valid configs if the server was
1615
+ # accessed directly by IP address under some situations.
1616
+ # Instead of raising an exception like in Werkzeug 0.7 or
1617
+ # earlier we go by an invalid subdomain which will result
1618
+ # in a 404 error on matching.
1619
+ warnings.warn(
1620
+ "Current server name '{}' doesn't match configured"
1621
+ " server name '{}'".format(wsgi_server_name, server_name),
1622
+ stacklevel=2,
1623
+ )
1624
+ subdomain = "<invalid>"
1625
+ else:
1626
+ subdomain = ".".join(filter(None, cur_server_name[:offset]))
1627
+
1628
+ def _get_wsgi_string(name):
1629
+ val = environ.get(name)
1630
+ if val is not None:
1631
+ return wsgi_decoding_dance(val, self.charset)
1632
+
1633
+ script_name = _get_wsgi_string("SCRIPT_NAME")
1634
+ path_info = _get_wsgi_string("PATH_INFO")
1635
+ query_args = _get_wsgi_string("QUERY_STRING")
1636
+ return Map.bind(
1637
+ self,
1638
+ server_name,
1639
+ script_name,
1640
+ subdomain,
1641
+ scheme,
1642
+ environ["REQUEST_METHOD"],
1643
+ path_info,
1644
+ query_args=query_args,
1645
+ )
1646
+
1647
+ def update(self):
1648
+ """Called before matching and building to keep the compiled rules
1649
+ in the correct order after things changed.
1650
+ """
1651
+ if not self._remap:
1652
+ return
1653
+
1654
+ with self._remap_lock:
1655
+ if not self._remap:
1656
+ return
1657
+
1658
+ self._rules.sort(key=lambda x: x.match_compare_key())
1659
+ for rules in itervalues(self._rules_by_endpoint):
1660
+ rules.sort(key=lambda x: x.build_compare_key())
1661
+ self._remap = False
1662
+
1663
+ def __repr__(self):
1664
+ rules = self.iter_rules()
1665
+ return "%s(%s)" % (self.__class__.__name__, pformat(list(rules)))
1666
+
1667
+
1668
+ class MapAdapter(object):
1669
+
1670
+ """Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
1671
+ the URL matching and building based on runtime information.
1672
+ """
1673
+
1674
+ def __init__(
1675
+ self,
1676
+ map,
1677
+ server_name,
1678
+ script_name,
1679
+ subdomain,
1680
+ url_scheme,
1681
+ path_info,
1682
+ default_method,
1683
+ query_args=None,
1684
+ ):
1685
+ self.map = map
1686
+ self.server_name = to_unicode(server_name)
1687
+ script_name = to_unicode(script_name)
1688
+ if not script_name.endswith(u"/"):
1689
+ script_name += u"/"
1690
+ self.script_name = script_name
1691
+ self.subdomain = to_unicode(subdomain)
1692
+ self.url_scheme = to_unicode(url_scheme)
1693
+ self.path_info = to_unicode(path_info)
1694
+ self.default_method = to_unicode(default_method)
1695
+ self.query_args = query_args
1696
+ self.websocket = self.url_scheme in {"ws", "wss"}
1697
+
1698
+ def dispatch(
1699
+ self, view_func, path_info=None, method=None, catch_http_exceptions=False
1700
+ ):
1701
+ """Does the complete dispatching process. `view_func` is called with
1702
+ the endpoint and a dict with the values for the view. It should
1703
+ look up the view function, call it, and return a response object
1704
+ or WSGI application. http exceptions are not caught by default
1705
+ so that applications can display nicer error messages by just
1706
+ catching them by hand. If you want to stick with the default
1707
+ error messages you can pass it ``catch_http_exceptions=True`` and
1708
+ it will catch the http exceptions.
1709
+
1710
+ Here a small example for the dispatch usage::
1711
+
1712
+ from pythonagent.vendor.werkzeug.wrappers import Request, Response
1713
+ from pythonagent.vendor.werkzeug.wsgi import responder
1714
+ from pythonagent.vendor.werkzeug.routing import Map, Rule
1715
+
1716
+ def on_index(request):
1717
+ return Response('Hello from the index')
1718
+
1719
+ url_map = Map([Rule('/', endpoint='index')])
1720
+ views = {'index': on_index}
1721
+
1722
+ @responder
1723
+ def application(environ, start_response):
1724
+ request = Request(environ)
1725
+ urls = url_map.bind_to_environ(environ)
1726
+ return urls.dispatch(lambda e, v: views[e](request, **v),
1727
+ catch_http_exceptions=True)
1728
+
1729
+ Keep in mind that this method might return exception objects, too, so
1730
+ use :class:`Response.force_type` to get a response object.
1731
+
1732
+ :param view_func: a function that is called with the endpoint as
1733
+ first argument and the value dict as second. Has
1734
+ to dispatch to the actual view function with this
1735
+ information. (see above)
1736
+ :param path_info: the path info to use for matching. Overrides the
1737
+ path info specified on binding.
1738
+ :param method: the HTTP method used for matching. Overrides the
1739
+ method specified on binding.
1740
+ :param catch_http_exceptions: set to `True` to catch any of the
1741
+ werkzeug :class:`HTTPException`\\s.
1742
+ """
1743
+ try:
1744
+ try:
1745
+ endpoint, args = self.match(path_info, method)
1746
+ except RequestRedirect as e:
1747
+ return e
1748
+ return view_func(endpoint, args)
1749
+ except HTTPException as e:
1750
+ if catch_http_exceptions:
1751
+ return e
1752
+ raise
1753
+
1754
+ def match(
1755
+ self,
1756
+ path_info=None,
1757
+ method=None,
1758
+ return_rule=False,
1759
+ query_args=None,
1760
+ websocket=None,
1761
+ ):
1762
+ """The usage is simple: you just pass the match method the current
1763
+ path info as well as the method (which defaults to `GET`). The
1764
+ following things can then happen:
1765
+
1766
+ - you receive a `NotFound` exception that indicates that no URL is
1767
+ matching. A `NotFound` exception is also a WSGI application you
1768
+ can call to get a default page not found page (happens to be the
1769
+ same object as `werkzeug.exceptions.NotFound`)
1770
+
1771
+ - you receive a `MethodNotAllowed` exception that indicates that there
1772
+ is a match for this URL but not for the current request method.
1773
+ This is useful for RESTful applications.
1774
+
1775
+ - you receive a `RequestRedirect` exception with a `new_url`
1776
+ attribute. This exception is used to notify you about a request
1777
+ Werkzeug requests from your WSGI application. This is for example the
1778
+ case if you request ``/foo`` although the correct URL is ``/foo/``
1779
+ You can use the `RequestRedirect` instance as response-like object
1780
+ similar to all other subclasses of `HTTPException`.
1781
+
1782
+ - you receive a ``WebsocketMismatch`` exception if the only
1783
+ match is a WebSocket rule but the bind is an HTTP request, or
1784
+ if the match is an HTTP rule but the bind is a WebSocket
1785
+ request.
1786
+
1787
+ - you get a tuple in the form ``(endpoint, arguments)`` if there is
1788
+ a match (unless `return_rule` is True, in which case you get a tuple
1789
+ in the form ``(rule, arguments)``)
1790
+
1791
+ If the path info is not passed to the match method the default path
1792
+ info of the map is used (defaults to the root URL if not defined
1793
+ explicitly).
1794
+
1795
+ All of the exceptions raised are subclasses of `HTTPException` so they
1796
+ can be used as WSGI responses. They will all render generic error or
1797
+ redirect pages.
1798
+
1799
+ Here is a small example for matching:
1800
+
1801
+ >>> m = Map([
1802
+ ... Rule('/', endpoint='index'),
1803
+ ... Rule('/downloads/', endpoint='downloads/index'),
1804
+ ... Rule('/downloads/<int:id>', endpoint='downloads/show')
1805
+ ... ])
1806
+ >>> urls = m.bind("example.com", "/")
1807
+ >>> urls.match("/", "GET")
1808
+ ('index', {})
1809
+ >>> urls.match("/downloads/42")
1810
+ ('downloads/show', {'id': 42})
1811
+
1812
+ And here is what happens on redirect and missing URLs:
1813
+
1814
+ >>> urls.match("/downloads")
1815
+ Traceback (most recent call last):
1816
+ ...
1817
+ RequestRedirect: http://example.com/downloads/
1818
+ >>> urls.match("/missing")
1819
+ Traceback (most recent call last):
1820
+ ...
1821
+ NotFound: 404 Not Found
1822
+
1823
+ :param path_info: the path info to use for matching. Overrides the
1824
+ path info specified on binding.
1825
+ :param method: the HTTP method used for matching. Overrides the
1826
+ method specified on binding.
1827
+ :param return_rule: return the rule that matched instead of just the
1828
+ endpoint (defaults to `False`).
1829
+ :param query_args: optional query arguments that are used for
1830
+ automatic redirects as string or dictionary. It's
1831
+ currently not possible to use the query arguments
1832
+ for URL matching.
1833
+ :param websocket: Match WebSocket instead of HTTP requests. A
1834
+ websocket request has a ``ws`` or ``wss``
1835
+ :attr:`url_scheme`. This overrides that detection.
1836
+
1837
+ .. versionadded:: 1.0
1838
+ Added ``websocket``.
1839
+
1840
+ .. versionchanged:: 0.8
1841
+ ``query_args`` can be a string.
1842
+
1843
+ .. versionadded:: 0.7
1844
+ Added ``query_args``.
1845
+
1846
+ .. versionadded:: 0.6
1847
+ Added ``return_rule``.
1848
+ """
1849
+ self.map.update()
1850
+ if path_info is None:
1851
+ path_info = self.path_info
1852
+ else:
1853
+ path_info = to_unicode(path_info, self.map.charset)
1854
+ if query_args is None:
1855
+ query_args = self.query_args
1856
+ method = (method or self.default_method).upper()
1857
+
1858
+ if websocket is None:
1859
+ websocket = self.websocket
1860
+
1861
+ require_redirect = False
1862
+
1863
+ path = u"%s|%s" % (
1864
+ self.map.host_matching and self.server_name or self.subdomain,
1865
+ path_info and "/%s" % path_info.lstrip("/"),
1866
+ )
1867
+
1868
+ have_match_for = set()
1869
+ websocket_mismatch = False
1870
+
1871
+ for rule in self.map._rules:
1872
+ try:
1873
+ rv = rule.match(path, method)
1874
+ except RequestPath as e:
1875
+ raise RequestRedirect(
1876
+ self.make_redirect_url(
1877
+ url_quote(e.path_info, self.map.charset, safe="/:|+"),
1878
+ query_args,
1879
+ )
1880
+ )
1881
+ except RequestAliasRedirect as e:
1882
+ raise RequestRedirect(
1883
+ self.make_alias_redirect_url(
1884
+ path, rule.endpoint, e.matched_values, method, query_args
1885
+ )
1886
+ )
1887
+ if rv is None:
1888
+ continue
1889
+ if rule.methods is not None and method not in rule.methods:
1890
+ have_match_for.update(rule.methods)
1891
+ continue
1892
+
1893
+ if rule.websocket != websocket:
1894
+ websocket_mismatch = True
1895
+ continue
1896
+
1897
+ if self.map.redirect_defaults:
1898
+ redirect_url = self.get_default_redirect(rule, method, rv, query_args)
1899
+ if redirect_url is not None:
1900
+ raise RequestRedirect(redirect_url)
1901
+
1902
+ if rule.redirect_to is not None:
1903
+ if isinstance(rule.redirect_to, string_types):
1904
+
1905
+ def _handle_match(match):
1906
+ value = rv[match.group(1)]
1907
+ return rule._converters[match.group(1)].to_url(value)
1908
+
1909
+ redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to)
1910
+ else:
1911
+ redirect_url = rule.redirect_to(self, **rv)
1912
+ raise RequestRedirect(
1913
+ str(
1914
+ url_join(
1915
+ "%s://%s%s%s"
1916
+ % (
1917
+ self.url_scheme or "http",
1918
+ self.subdomain + "." if self.subdomain else "",
1919
+ self.server_name,
1920
+ self.script_name,
1921
+ ),
1922
+ redirect_url,
1923
+ )
1924
+ )
1925
+ )
1926
+
1927
+ if require_redirect:
1928
+ raise RequestRedirect(
1929
+ self.make_redirect_url(
1930
+ url_quote(path_info, self.map.charset, safe="/:|+"), query_args
1931
+ )
1932
+ )
1933
+
1934
+ if return_rule:
1935
+ return rule, rv
1936
+ else:
1937
+ return rule.endpoint, rv
1938
+
1939
+ if have_match_for:
1940
+ raise MethodNotAllowed(valid_methods=list(have_match_for))
1941
+
1942
+ if websocket_mismatch:
1943
+ raise WebsocketMismatch()
1944
+
1945
+ raise NotFound()
1946
+
1947
+ def test(self, path_info=None, method=None):
1948
+ """Test if a rule would match. Works like `match` but returns `True`
1949
+ if the URL matches, or `False` if it does not exist.
1950
+
1951
+ :param path_info: the path info to use for matching. Overrides the
1952
+ path info specified on binding.
1953
+ :param method: the HTTP method used for matching. Overrides the
1954
+ method specified on binding.
1955
+ """
1956
+ try:
1957
+ self.match(path_info, method)
1958
+ except RequestRedirect:
1959
+ pass
1960
+ except HTTPException:
1961
+ return False
1962
+ return True
1963
+
1964
+ def allowed_methods(self, path_info=None):
1965
+ """Returns the valid methods that match for a given path.
1966
+
1967
+ .. versionadded:: 0.7
1968
+ """
1969
+ try:
1970
+ self.match(path_info, method="--")
1971
+ except MethodNotAllowed as e:
1972
+ return e.valid_methods
1973
+ except HTTPException:
1974
+ pass
1975
+ return []
1976
+
1977
+ def get_host(self, domain_part):
1978
+ """Figures out the full host name for the given domain part. The
1979
+ domain part is a subdomain in case host matching is disabled or
1980
+ a full host name.
1981
+ """
1982
+ if self.map.host_matching:
1983
+ if domain_part is None:
1984
+ return self.server_name
1985
+ return to_unicode(domain_part, "ascii")
1986
+ subdomain = domain_part
1987
+ if subdomain is None:
1988
+ subdomain = self.subdomain
1989
+ else:
1990
+ subdomain = to_unicode(subdomain, "ascii")
1991
+ return (subdomain + u"." if subdomain else u"") + self.server_name
1992
+
1993
+ def get_default_redirect(self, rule, method, values, query_args):
1994
+ """A helper that returns the URL to redirect to if it finds one.
1995
+ This is used for default redirecting only.
1996
+
1997
+ :internal:
1998
+ """
1999
+ assert self.map.redirect_defaults
2000
+ for r in self.map._rules_by_endpoint[rule.endpoint]:
2001
+ # every rule that comes after this one, including ourself
2002
+ # has a lower priority for the defaults. We order the ones
2003
+ # with the highest priority up for building.
2004
+ if r is rule:
2005
+ break
2006
+ if r.provides_defaults_for(rule) and r.suitable_for(values, method):
2007
+ values.update(r.defaults)
2008
+ domain_part, path = r.build(values)
2009
+ return self.make_redirect_url(path, query_args, domain_part=domain_part)
2010
+
2011
+ def encode_query_args(self, query_args):
2012
+ if not isinstance(query_args, string_types):
2013
+ query_args = url_encode(query_args, self.map.charset)
2014
+ return query_args
2015
+
2016
+ def make_redirect_url(self, path_info, query_args=None, domain_part=None):
2017
+ """Creates a redirect URL.
2018
+
2019
+ :internal:
2020
+ """
2021
+ suffix = ""
2022
+ if query_args:
2023
+ suffix = "?" + self.encode_query_args(query_args)
2024
+ return str(
2025
+ "%s://%s/%s%s"
2026
+ % (
2027
+ self.url_scheme or "http",
2028
+ self.get_host(domain_part),
2029
+ posixpath.join(
2030
+ self.script_name[:-1].lstrip("/"), path_info.lstrip("/")
2031
+ ),
2032
+ suffix,
2033
+ )
2034
+ )
2035
+
2036
+ def make_alias_redirect_url(self, path, endpoint, values, method, query_args):
2037
+ """Internally called to make an alias redirect URL."""
2038
+ url = self.build(
2039
+ endpoint, values, method, append_unknown=False, force_external=True
2040
+ )
2041
+ if query_args:
2042
+ url += "?" + self.encode_query_args(query_args)
2043
+ assert url != path, "detected invalid alias setting. No canonical URL found"
2044
+ return url
2045
+
2046
+ def _partial_build(self, endpoint, values, method, append_unknown):
2047
+ """Helper for :meth:`build`. Returns subdomain and path for the
2048
+ rule that accepts this endpoint, values and method.
2049
+
2050
+ :internal:
2051
+ """
2052
+ # in case the method is none, try with the default method first
2053
+ if method is None:
2054
+ rv = self._partial_build(
2055
+ endpoint, values, self.default_method, append_unknown
2056
+ )
2057
+ if rv is not None:
2058
+ return rv
2059
+
2060
+ # Default method did not match or a specific method is passed.
2061
+ # Check all for first match with matching host. If no matching
2062
+ # host is found, go with first result.
2063
+ first_match = None
2064
+
2065
+ for rule in self.map._rules_by_endpoint.get(endpoint, ()):
2066
+ if rule.suitable_for(values, method):
2067
+ rv = rule.build(values, append_unknown)
2068
+
2069
+ if rv is not None:
2070
+ rv = (rv[0], rv[1], rule.websocket)
2071
+ if self.map.host_matching:
2072
+ if rv[0] == self.server_name:
2073
+ return rv
2074
+ elif first_match is None:
2075
+ first_match = rv
2076
+ else:
2077
+ return rv
2078
+
2079
+ return first_match
2080
+
2081
+ def build(
2082
+ self,
2083
+ endpoint,
2084
+ values=None,
2085
+ method=None,
2086
+ force_external=False,
2087
+ append_unknown=True,
2088
+ ):
2089
+ """Building URLs works pretty much the other way round. Instead of
2090
+ `match` you call `build` and pass it the endpoint and a dict of
2091
+ arguments for the placeholders.
2092
+
2093
+ The `build` function also accepts an argument called `force_external`
2094
+ which, if you set it to `True` will force external URLs. Per default
2095
+ external URLs (include the server name) will only be used if the
2096
+ target URL is on a different subdomain.
2097
+
2098
+ >>> m = Map([
2099
+ ... Rule('/', endpoint='index'),
2100
+ ... Rule('/downloads/', endpoint='downloads/index'),
2101
+ ... Rule('/downloads/<int:id>', endpoint='downloads/show')
2102
+ ... ])
2103
+ >>> urls = m.bind("example.com", "/")
2104
+ >>> urls.build("index", {})
2105
+ '/'
2106
+ >>> urls.build("downloads/show", {'id': 42})
2107
+ '/downloads/42'
2108
+ >>> urls.build("downloads/show", {'id': 42}, force_external=True)
2109
+ 'http://example.com/downloads/42'
2110
+
2111
+ Because URLs cannot contain non ASCII data you will always get
2112
+ bytestrings back. Non ASCII characters are urlencoded with the
2113
+ charset defined on the map instance.
2114
+
2115
+ Additional values are converted to unicode and appended to the URL as
2116
+ URL querystring parameters:
2117
+
2118
+ >>> urls.build("index", {'q': 'My Searchstring'})
2119
+ '/?q=My+Searchstring'
2120
+
2121
+ When processing those additional values, lists are furthermore
2122
+ interpreted as multiple values (as per
2123
+ :py:class:`werkzeug.datastructures.MultiDict`):
2124
+
2125
+ >>> urls.build("index", {'q': ['a', 'b', 'c']})
2126
+ '/?q=a&q=b&q=c'
2127
+
2128
+ Passing a ``MultiDict`` will also add multiple values:
2129
+
2130
+ >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
2131
+ '/?p=z&q=a&q=b'
2132
+
2133
+ If a rule does not exist when building a `BuildError` exception is
2134
+ raised.
2135
+
2136
+ The build method accepts an argument called `method` which allows you
2137
+ to specify the method you want to have an URL built for if you have
2138
+ different methods for the same endpoint specified.
2139
+
2140
+ .. versionadded:: 0.6
2141
+ the `append_unknown` parameter was added.
2142
+
2143
+ :param endpoint: the endpoint of the URL to build.
2144
+ :param values: the values for the URL to build. Unhandled values are
2145
+ appended to the URL as query parameters.
2146
+ :param method: the HTTP method for the rule if there are different
2147
+ URLs for different methods on the same endpoint.
2148
+ :param force_external: enforce full canonical external URLs. If the URL
2149
+ scheme is not provided, this will generate
2150
+ a protocol-relative URL.
2151
+ :param append_unknown: unknown parameters are appended to the generated
2152
+ URL as query string argument. Disable this
2153
+ if you want the builder to ignore those.
2154
+ """
2155
+ self.map.update()
2156
+
2157
+ if values:
2158
+ if isinstance(values, MultiDict):
2159
+ temp_values = {}
2160
+ # iteritems(dict, values) is like `values.lists()`
2161
+ # without the call or `list()` coercion overhead.
2162
+ for key, value in iteritems(dict, values):
2163
+ if not value:
2164
+ continue
2165
+ if len(value) == 1: # flatten single item lists
2166
+ value = value[0]
2167
+ if value is None: # drop None
2168
+ continue
2169
+ temp_values[key] = value
2170
+ values = temp_values
2171
+ else:
2172
+ # drop None
2173
+ values = dict(i for i in iteritems(values) if i[1] is not None)
2174
+ else:
2175
+ values = {}
2176
+
2177
+ rv = self._partial_build(endpoint, values, method, append_unknown)
2178
+ if rv is None:
2179
+ raise BuildError(endpoint, values, method, self)
2180
+
2181
+ domain_part, path, websocket = rv
2182
+ host = self.get_host(domain_part)
2183
+
2184
+ # Always build WebSocket routes with the scheme (browsers
2185
+ # require full URLs). If bound to a WebSocket, ensure that HTTP
2186
+ # routes are built with an HTTP scheme.
2187
+ url_scheme = self.url_scheme
2188
+ secure = url_scheme in {"https", "wss"}
2189
+
2190
+ if websocket:
2191
+ force_external = True
2192
+ url_scheme = "wss" if secure else "ws"
2193
+ elif url_scheme:
2194
+ url_scheme = "https" if secure else "http"
2195
+
2196
+ # shortcut this.
2197
+ if not force_external and (
2198
+ (self.map.host_matching and host == self.server_name)
2199
+ or (not self.map.host_matching and domain_part == self.subdomain)
2200
+ ):
2201
+ return "%s/%s" % (self.script_name.rstrip("/"), path.lstrip("/"))
2202
+ return str(
2203
+ "%s//%s%s/%s"
2204
+ % (
2205
+ url_scheme + ":" if url_scheme else "",
2206
+ host,
2207
+ self.script_name[:-1],
2208
+ path.lstrip("/"),
2209
+ )
2210
+ )