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,1138 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ werkzeug.urls
4
+ ~~~~~~~~~~~~~
5
+
6
+ ``werkzeug.urls`` used to provide several wrapper functions for Python 2
7
+ urlparse, whose main purpose were to work around the behavior of the Py2
8
+ stdlib and its lack of unicode support. While this was already a somewhat
9
+ inconvenient situation, it got even more complicated because Python 3's
10
+ ``urllib.parse`` actually does handle unicode properly. In other words,
11
+ this module would wrap two libraries with completely different behavior. So
12
+ now this module contains a 2-and-3-compatible backport of Python 3's
13
+ ``urllib.parse``, which is mostly API-compatible.
14
+
15
+ :copyright: 2007 Pallets
16
+ :license: BSD-3-Clause
17
+ """
18
+ import codecs
19
+ import os
20
+ import re
21
+ from collections import namedtuple
22
+
23
+ from ._compat import fix_tuple_repr
24
+ from ._compat import implements_to_string
25
+ from ._compat import make_literal_wrapper
26
+ from ._compat import normalize_string_tuple
27
+ from ._compat import PY2
28
+ from ._compat import text_type
29
+ from ._compat import to_native
30
+ from ._compat import to_unicode
31
+ from ._compat import try_coerce_native
32
+ from ._internal import _decode_idna
33
+ from ._internal import _encode_idna
34
+
35
+ # A regular expression for what a valid schema looks like
36
+ _scheme_re = re.compile(r"^[a-zA-Z0-9+-.]+$")
37
+
38
+ # Characters that are safe in any part of an URL.
39
+ _always_safe = frozenset(
40
+ bytearray(
41
+ b"abcdefghijklmnopqrstuvwxyz"
42
+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
43
+ b"0123456789"
44
+ b"-._~"
45
+ )
46
+ )
47
+
48
+ _hexdigits = "0123456789ABCDEFabcdef"
49
+ _hextobyte = dict(
50
+ ((a + b).encode(), int(a + b, 16)) for a in _hexdigits for b in _hexdigits
51
+ )
52
+ _bytetohex = [("%%%02X" % char).encode("ascii") for char in range(256)]
53
+
54
+
55
+ _URLTuple = fix_tuple_repr(
56
+ namedtuple("_URLTuple", ["scheme", "netloc", "path", "query", "fragment"])
57
+ )
58
+
59
+
60
+ class BaseURL(_URLTuple):
61
+ """Superclass of :py:class:`URL` and :py:class:`BytesURL`."""
62
+
63
+ __slots__ = ()
64
+
65
+ def replace(self, **kwargs):
66
+ """Return an URL with the same values, except for those parameters
67
+ given new values by whichever keyword arguments are specified."""
68
+ return self._replace(**kwargs)
69
+
70
+ @property
71
+ def host(self):
72
+ """The host part of the URL if available, otherwise `None`. The
73
+ host is either the hostname or the IP address mentioned in the
74
+ URL. It will not contain the port.
75
+ """
76
+ return self._split_host()[0]
77
+
78
+ @property
79
+ def ascii_host(self):
80
+ """Works exactly like :attr:`host` but will return a result that
81
+ is restricted to ASCII. If it finds a netloc that is not ASCII
82
+ it will attempt to idna decode it. This is useful for socket
83
+ operations when the URL might include internationalized characters.
84
+ """
85
+ rv = self.host
86
+ if rv is not None and isinstance(rv, text_type):
87
+ try:
88
+ rv = _encode_idna(rv)
89
+ except UnicodeError:
90
+ rv = rv.encode("ascii", "ignore")
91
+ return to_native(rv, "ascii", "ignore")
92
+
93
+ @property
94
+ def port(self):
95
+ """The port in the URL as an integer if it was present, `None`
96
+ otherwise. This does not fill in default ports.
97
+ """
98
+ try:
99
+ rv = int(to_native(self._split_host()[1]))
100
+ if 0 <= rv <= 65535:
101
+ return rv
102
+ except (ValueError, TypeError):
103
+ pass
104
+
105
+ @property
106
+ def auth(self):
107
+ """The authentication part in the URL if available, `None`
108
+ otherwise.
109
+ """
110
+ return self._split_netloc()[0]
111
+
112
+ @property
113
+ def username(self):
114
+ """The username if it was part of the URL, `None` otherwise.
115
+ This undergoes URL decoding and will always be a unicode string.
116
+ """
117
+ rv = self._split_auth()[0]
118
+ if rv is not None:
119
+ return _url_unquote_legacy(rv)
120
+
121
+ @property
122
+ def raw_username(self):
123
+ """The username if it was part of the URL, `None` otherwise.
124
+ Unlike :attr:`username` this one is not being decoded.
125
+ """
126
+ return self._split_auth()[0]
127
+
128
+ @property
129
+ def password(self):
130
+ """The password if it was part of the URL, `None` otherwise.
131
+ This undergoes URL decoding and will always be a unicode string.
132
+ """
133
+ rv = self._split_auth()[1]
134
+ if rv is not None:
135
+ return _url_unquote_legacy(rv)
136
+
137
+ @property
138
+ def raw_password(self):
139
+ """The password if it was part of the URL, `None` otherwise.
140
+ Unlike :attr:`password` this one is not being decoded.
141
+ """
142
+ return self._split_auth()[1]
143
+
144
+ def decode_query(self, *args, **kwargs):
145
+ """Decodes the query part of the URL. Ths is a shortcut for
146
+ calling :func:`url_decode` on the query argument. The arguments and
147
+ keyword arguments are forwarded to :func:`url_decode` unchanged.
148
+ """
149
+ return url_decode(self.query, *args, **kwargs)
150
+
151
+ def join(self, *args, **kwargs):
152
+ """Joins this URL with another one. This is just a convenience
153
+ function for calling into :meth:`url_join` and then parsing the
154
+ return value again.
155
+ """
156
+ return url_parse(url_join(self, *args, **kwargs))
157
+
158
+ def to_url(self):
159
+ """Returns a URL string or bytes depending on the type of the
160
+ information stored. This is just a convenience function
161
+ for calling :meth:`url_unparse` for this URL.
162
+ """
163
+ return url_unparse(self)
164
+
165
+ def decode_netloc(self):
166
+ """Decodes the netloc part into a string."""
167
+ rv = _decode_idna(self.host or "")
168
+
169
+ if ":" in rv:
170
+ rv = "[%s]" % rv
171
+ port = self.port
172
+ if port is not None:
173
+ rv = "%s:%d" % (rv, port)
174
+ auth = ":".join(
175
+ filter(
176
+ None,
177
+ [
178
+ _url_unquote_legacy(self.raw_username or "", "/:%@"),
179
+ _url_unquote_legacy(self.raw_password or "", "/:%@"),
180
+ ],
181
+ )
182
+ )
183
+ if auth:
184
+ rv = "%s@%s" % (auth, rv)
185
+ return rv
186
+
187
+ def to_uri_tuple(self):
188
+ """Returns a :class:`BytesURL` tuple that holds a URI. This will
189
+ encode all the information in the URL properly to ASCII using the
190
+ rules a web browser would follow.
191
+
192
+ It's usually more interesting to directly call :meth:`iri_to_uri` which
193
+ will return a string.
194
+ """
195
+ return url_parse(iri_to_uri(self).encode("ascii"))
196
+
197
+ def to_iri_tuple(self):
198
+ """Returns a :class:`URL` tuple that holds a IRI. This will try
199
+ to decode as much information as possible in the URL without
200
+ losing information similar to how a web browser does it for the
201
+ URL bar.
202
+
203
+ It's usually more interesting to directly call :meth:`uri_to_iri` which
204
+ will return a string.
205
+ """
206
+ return url_parse(uri_to_iri(self))
207
+
208
+ def get_file_location(self, pathformat=None):
209
+ """Returns a tuple with the location of the file in the form
210
+ ``(server, location)``. If the netloc is empty in the URL or
211
+ points to localhost, it's represented as ``None``.
212
+
213
+ The `pathformat` by default is autodetection but needs to be set
214
+ when working with URLs of a specific system. The supported values
215
+ are ``'windows'`` when working with Windows or DOS paths and
216
+ ``'posix'`` when working with posix paths.
217
+
218
+ If the URL does not point to a local file, the server and location
219
+ are both represented as ``None``.
220
+
221
+ :param pathformat: The expected format of the path component.
222
+ Currently ``'windows'`` and ``'posix'`` are
223
+ supported. Defaults to ``None`` which is
224
+ autodetect.
225
+ """
226
+ if self.scheme != "file":
227
+ return None, None
228
+
229
+ path = url_unquote(self.path)
230
+ host = self.netloc or None
231
+
232
+ if pathformat is None:
233
+ if os.name == "nt":
234
+ pathformat = "windows"
235
+ else:
236
+ pathformat = "posix"
237
+
238
+ if pathformat == "windows":
239
+ if path[:1] == "/" and path[1:2].isalpha() and path[2:3] in "|:":
240
+ path = path[1:2] + ":" + path[3:]
241
+ windows_share = path[:3] in ("\\" * 3, "/" * 3)
242
+ import ntpath
243
+
244
+ path = ntpath.normpath(path)
245
+ # Windows shared drives are represented as ``\\host\\directory``.
246
+ # That results in a URL like ``file://///host/directory``, and a
247
+ # path like ``///host/directory``. We need to special-case this
248
+ # because the path contains the hostname.
249
+ if windows_share and host is None:
250
+ parts = path.lstrip("\\").split("\\", 1)
251
+ if len(parts) == 2:
252
+ host, path = parts
253
+ else:
254
+ host = parts[0]
255
+ path = ""
256
+ elif pathformat == "posix":
257
+ import posixpath
258
+
259
+ path = posixpath.normpath(path)
260
+ else:
261
+ raise TypeError("Invalid path format %s" % repr(pathformat))
262
+
263
+ if host in ("127.0.0.1", "::1", "localhost"):
264
+ host = None
265
+
266
+ return host, path
267
+
268
+ def _split_netloc(self):
269
+ if self._at in self.netloc:
270
+ return self.netloc.split(self._at, 1)
271
+ return None, self.netloc
272
+
273
+ def _split_auth(self):
274
+ auth = self._split_netloc()[0]
275
+ if not auth:
276
+ return None, None
277
+ if self._colon not in auth:
278
+ return auth, None
279
+ return auth.split(self._colon, 1)
280
+
281
+ def _split_host(self):
282
+ rv = self._split_netloc()[1]
283
+ if not rv:
284
+ return None, None
285
+
286
+ if not rv.startswith(self._lbracket):
287
+ if self._colon in rv:
288
+ return rv.split(self._colon, 1)
289
+ return rv, None
290
+
291
+ idx = rv.find(self._rbracket)
292
+ if idx < 0:
293
+ return rv, None
294
+
295
+ host = rv[1:idx]
296
+ rest = rv[idx + 1 :]
297
+ if rest.startswith(self._colon):
298
+ return host, rest[1:]
299
+ return host, None
300
+
301
+
302
+ @implements_to_string
303
+ class URL(BaseURL):
304
+ """Represents a parsed URL. This behaves like a regular tuple but
305
+ also has some extra attributes that give further insight into the
306
+ URL.
307
+ """
308
+
309
+ __slots__ = ()
310
+ _at = "@"
311
+ _colon = ":"
312
+ _lbracket = "["
313
+ _rbracket = "]"
314
+
315
+ def __str__(self):
316
+ return self.to_url()
317
+
318
+ def encode_netloc(self):
319
+ """Encodes the netloc part to an ASCII safe URL as bytes."""
320
+ rv = self.ascii_host or ""
321
+ if ":" in rv:
322
+ rv = "[%s]" % rv
323
+ port = self.port
324
+ if port is not None:
325
+ rv = "%s:%d" % (rv, port)
326
+ auth = ":".join(
327
+ filter(
328
+ None,
329
+ [
330
+ url_quote(self.raw_username or "", "utf-8", "strict", "/:%"),
331
+ url_quote(self.raw_password or "", "utf-8", "strict", "/:%"),
332
+ ],
333
+ )
334
+ )
335
+ if auth:
336
+ rv = "%s@%s" % (auth, rv)
337
+ return to_native(rv)
338
+
339
+ def encode(self, charset="utf-8", errors="replace"):
340
+ """Encodes the URL to a tuple made out of bytes. The charset is
341
+ only being used for the path, query and fragment.
342
+ """
343
+ return BytesURL(
344
+ self.scheme.encode("ascii"),
345
+ self.encode_netloc(),
346
+ self.path.encode(charset, errors),
347
+ self.query.encode(charset, errors),
348
+ self.fragment.encode(charset, errors),
349
+ )
350
+
351
+
352
+ class BytesURL(BaseURL):
353
+ """Represents a parsed URL in bytes."""
354
+
355
+ __slots__ = ()
356
+ _at = b"@"
357
+ _colon = b":"
358
+ _lbracket = b"["
359
+ _rbracket = b"]"
360
+
361
+ def __str__(self):
362
+ return self.to_url().decode("utf-8", "replace")
363
+
364
+ def encode_netloc(self):
365
+ """Returns the netloc unchanged as bytes."""
366
+ return self.netloc
367
+
368
+ def decode(self, charset="utf-8", errors="replace"):
369
+ """Decodes the URL to a tuple made out of strings. The charset is
370
+ only being used for the path, query and fragment.
371
+ """
372
+ return URL(
373
+ self.scheme.decode("ascii"),
374
+ self.decode_netloc(),
375
+ self.path.decode(charset, errors),
376
+ self.query.decode(charset, errors),
377
+ self.fragment.decode(charset, errors),
378
+ )
379
+
380
+
381
+ _unquote_maps = {frozenset(): _hextobyte}
382
+
383
+
384
+ def _unquote_to_bytes(string, unsafe=""):
385
+ if isinstance(string, text_type):
386
+ string = string.encode("utf-8")
387
+
388
+ if isinstance(unsafe, text_type):
389
+ unsafe = unsafe.encode("utf-8")
390
+
391
+ unsafe = frozenset(bytearray(unsafe))
392
+ groups = iter(string.split(b"%"))
393
+ result = bytearray(next(groups, b""))
394
+
395
+ try:
396
+ hex_to_byte = _unquote_maps[unsafe]
397
+ except KeyError:
398
+ hex_to_byte = _unquote_maps[unsafe] = {
399
+ h: b for h, b in _hextobyte.items() if b not in unsafe
400
+ }
401
+
402
+ for group in groups:
403
+ code = group[:2]
404
+
405
+ if code in hex_to_byte:
406
+ result.append(hex_to_byte[code])
407
+ result.extend(group[2:])
408
+ else:
409
+ result.append(37) # %
410
+ result.extend(group)
411
+
412
+ return bytes(result)
413
+
414
+
415
+ def _url_encode_impl(obj, charset, encode_keys, sort, key):
416
+ from .datastructures import iter_multi_items
417
+
418
+ iterable = iter_multi_items(obj)
419
+ if sort:
420
+ iterable = sorted(iterable, key=key)
421
+ for key, value in iterable:
422
+ if value is None:
423
+ continue
424
+ if not isinstance(key, bytes):
425
+ key = text_type(key).encode(charset)
426
+ if not isinstance(value, bytes):
427
+ value = text_type(value).encode(charset)
428
+ yield _fast_url_quote_plus(key) + "=" + _fast_url_quote_plus(value)
429
+
430
+
431
+ def _url_unquote_legacy(value, unsafe=""):
432
+ try:
433
+ return url_unquote(value, charset="utf-8", errors="strict", unsafe=unsafe)
434
+ except UnicodeError:
435
+ return url_unquote(value, charset="latin1", unsafe=unsafe)
436
+
437
+
438
+ def url_parse(url, scheme=None, allow_fragments=True):
439
+ """Parses a URL from a string into a :class:`URL` tuple. If the URL
440
+ is lacking a scheme it can be provided as second argument. Otherwise,
441
+ it is ignored. Optionally fragments can be stripped from the URL
442
+ by setting `allow_fragments` to `False`.
443
+
444
+ The inverse of this function is :func:`url_unparse`.
445
+
446
+ :param url: the URL to parse.
447
+ :param scheme: the default schema to use if the URL is schemaless.
448
+ :param allow_fragments: if set to `False` a fragment will be removed
449
+ from the URL.
450
+ """
451
+ s = make_literal_wrapper(url)
452
+ is_text_based = isinstance(url, text_type)
453
+
454
+ if scheme is None:
455
+ scheme = s("")
456
+ netloc = query = fragment = s("")
457
+ i = url.find(s(":"))
458
+ if i > 0 and _scheme_re.match(to_native(url[:i], errors="replace")):
459
+ # make sure "iri" is not actually a port number (in which case
460
+ # "scheme" is really part of the path)
461
+ rest = url[i + 1 :]
462
+ if not rest or any(c not in s("0123456789") for c in rest):
463
+ # not a port number
464
+ scheme, url = url[:i].lower(), rest
465
+
466
+ if url[:2] == s("//"):
467
+ delim = len(url)
468
+ for c in s("/?#"):
469
+ wdelim = url.find(c, 2)
470
+ if wdelim >= 0:
471
+ delim = min(delim, wdelim)
472
+ netloc, url = url[2:delim], url[delim:]
473
+ if (s("[") in netloc and s("]") not in netloc) or (
474
+ s("]") in netloc and s("[") not in netloc
475
+ ):
476
+ raise ValueError("Invalid IPv6 URL")
477
+
478
+ if allow_fragments and s("#") in url:
479
+ url, fragment = url.split(s("#"), 1)
480
+ if s("?") in url:
481
+ url, query = url.split(s("?"), 1)
482
+
483
+ result_type = URL if is_text_based else BytesURL
484
+ return result_type(scheme, netloc, url, query, fragment)
485
+
486
+
487
+ def _make_fast_url_quote(charset="utf-8", errors="strict", safe="/:", unsafe=""):
488
+ """Precompile the translation table for a URL encoding function.
489
+
490
+ Unlike :func:`url_quote`, the generated function only takes the
491
+ string to quote.
492
+
493
+ :param charset: The charset to encode the result with.
494
+ :param errors: How to handle encoding errors.
495
+ :param safe: An optional sequence of safe characters to never encode.
496
+ :param unsafe: An optional sequence of unsafe characters to always encode.
497
+ """
498
+ if isinstance(safe, text_type):
499
+ safe = safe.encode(charset, errors)
500
+
501
+ if isinstance(unsafe, text_type):
502
+ unsafe = unsafe.encode(charset, errors)
503
+
504
+ safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe))
505
+ table = [chr(c) if c in safe else "%%%02X" % c for c in range(256)]
506
+
507
+ if not PY2:
508
+
509
+ def quote(string):
510
+ return "".join([table[c] for c in string])
511
+
512
+ else:
513
+
514
+ def quote(string):
515
+ return "".join([table[c] for c in bytearray(string)])
516
+
517
+ return quote
518
+
519
+
520
+ _fast_url_quote = _make_fast_url_quote()
521
+ _fast_quote_plus = _make_fast_url_quote(safe=" ", unsafe="+")
522
+
523
+
524
+ def _fast_url_quote_plus(string):
525
+ return _fast_quote_plus(string).replace(" ", "+")
526
+
527
+
528
+ def url_quote(string, charset="utf-8", errors="strict", safe="/:", unsafe=""):
529
+ """URL encode a single string with a given encoding.
530
+
531
+ :param s: the string to quote.
532
+ :param charset: the charset to be used.
533
+ :param safe: an optional sequence of safe characters.
534
+ :param unsafe: an optional sequence of unsafe characters.
535
+
536
+ .. versionadded:: 0.9.2
537
+ The `unsafe` parameter was added.
538
+ """
539
+ if not isinstance(string, (text_type, bytes, bytearray)):
540
+ string = text_type(string)
541
+ if isinstance(string, text_type):
542
+ string = string.encode(charset, errors)
543
+ if isinstance(safe, text_type):
544
+ safe = safe.encode(charset, errors)
545
+ if isinstance(unsafe, text_type):
546
+ unsafe = unsafe.encode(charset, errors)
547
+ safe = (frozenset(bytearray(safe)) | _always_safe) - frozenset(bytearray(unsafe))
548
+ rv = bytearray()
549
+ for char in bytearray(string):
550
+ if char in safe:
551
+ rv.append(char)
552
+ else:
553
+ rv.extend(_bytetohex[char])
554
+ return to_native(bytes(rv))
555
+
556
+
557
+ def url_quote_plus(string, charset="utf-8", errors="strict", safe=""):
558
+ """URL encode a single string with the given encoding and convert
559
+ whitespace to "+".
560
+
561
+ :param s: The string to quote.
562
+ :param charset: The charset to be used.
563
+ :param safe: An optional sequence of safe characters.
564
+ """
565
+ return url_quote(string, charset, errors, safe + " ", "+").replace(" ", "+")
566
+
567
+
568
+ def url_unparse(components):
569
+ """The reverse operation to :meth:`url_parse`. This accepts arbitrary
570
+ as well as :class:`URL` tuples and returns a URL as a string.
571
+
572
+ :param components: the parsed URL as tuple which should be converted
573
+ into a URL string.
574
+ """
575
+ scheme, netloc, path, query, fragment = normalize_string_tuple(components)
576
+ s = make_literal_wrapper(scheme)
577
+ url = s("")
578
+
579
+ # We generally treat file:///x and file:/x the same which is also
580
+ # what browsers seem to do. This also allows us to ignore a schema
581
+ # register for netloc utilization or having to differentiate between
582
+ # empty and missing netloc.
583
+ if netloc or (scheme and path.startswith(s("/"))):
584
+ if path and path[:1] != s("/"):
585
+ path = s("/") + path
586
+ url = s("//") + (netloc or s("")) + path
587
+ elif path:
588
+ url += path
589
+ if scheme:
590
+ url = scheme + s(":") + url
591
+ if query:
592
+ url = url + s("?") + query
593
+ if fragment:
594
+ url = url + s("#") + fragment
595
+ return url
596
+
597
+
598
+ def url_unquote(string, charset="utf-8", errors="replace", unsafe=""):
599
+ """URL decode a single string with a given encoding. If the charset
600
+ is set to `None` no unicode decoding is performed and raw bytes
601
+ are returned.
602
+
603
+ :param s: the string to unquote.
604
+ :param charset: the charset of the query string. If set to `None`
605
+ no unicode decoding will take place.
606
+ :param errors: the error handling for the charset decoding.
607
+ """
608
+ rv = _unquote_to_bytes(string, unsafe)
609
+ if charset is not None:
610
+ rv = rv.decode(charset, errors)
611
+ return rv
612
+
613
+
614
+ def url_unquote_plus(s, charset="utf-8", errors="replace"):
615
+ """URL decode a single string with the given `charset` and decode "+" to
616
+ whitespace.
617
+
618
+ Per default encoding errors are ignored. If you want a different behavior
619
+ you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
620
+ :exc:`HTTPUnicodeError` is raised.
621
+
622
+ :param s: The string to unquote.
623
+ :param charset: the charset of the query string. If set to `None`
624
+ no unicode decoding will take place.
625
+ :param errors: The error handling for the `charset` decoding.
626
+ """
627
+ if isinstance(s, text_type):
628
+ s = s.replace(u"+", u" ")
629
+ else:
630
+ s = s.replace(b"+", b" ")
631
+ return url_unquote(s, charset, errors)
632
+
633
+
634
+ def url_fix(s, charset="utf-8"):
635
+ r"""Sometimes you get an URL by a user that just isn't a real URL because
636
+ it contains unsafe characters like ' ' and so on. This function can fix
637
+ some of the problems in a similar way browsers handle data entered by the
638
+ user:
639
+
640
+ >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
641
+ 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
642
+
643
+ :param s: the string with the URL to fix.
644
+ :param charset: The target charset for the URL if the url was given as
645
+ unicode string.
646
+ """
647
+ # First step is to switch to unicode processing and to convert
648
+ # backslashes (which are invalid in URLs anyways) to slashes. This is
649
+ # consistent with what Chrome does.
650
+ s = to_unicode(s, charset, "replace").replace("\\", "/")
651
+
652
+ # For the specific case that we look like a malformed windows URL
653
+ # we want to fix this up manually:
654
+ if s.startswith("file://") and s[7:8].isalpha() and s[8:10] in (":/", "|/"):
655
+ s = "file:///" + s[7:]
656
+
657
+ url = url_parse(s)
658
+ path = url_quote(url.path, charset, safe="/%+$!*'(),")
659
+ qs = url_quote_plus(url.query, charset, safe=":&%=+$!*'(),")
660
+ anchor = url_quote_plus(url.fragment, charset, safe=":&%=+$!*'(),")
661
+ return to_native(url_unparse((url.scheme, url.encode_netloc(), path, qs, anchor)))
662
+
663
+
664
+ # not-unreserved characters remain quoted when unquoting to IRI
665
+ _to_iri_unsafe = "".join([chr(c) for c in range(128) if c not in _always_safe])
666
+
667
+
668
+ def _codec_error_url_quote(e):
669
+ """Used in :func:`uri_to_iri` after unquoting to re-quote any
670
+ invalid bytes.
671
+ """
672
+ out = _fast_url_quote(e.object[e.start : e.end])
673
+
674
+ if PY2:
675
+ out = out.decode("utf-8")
676
+
677
+ return out, e.end
678
+
679
+
680
+ codecs.register_error("werkzeug.url_quote", _codec_error_url_quote)
681
+
682
+
683
+ def uri_to_iri(uri, charset="utf-8", errors="werkzeug.url_quote"):
684
+ """Convert a URI to an IRI. All valid UTF-8 characters are unquoted,
685
+ leaving all reserved and invalid characters quoted. If the URL has
686
+ a domain, it is decoded from Punycode.
687
+
688
+ >>> uri_to_iri("http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF")
689
+ 'http://\\u2603.net/p\\xe5th?q=\\xe8ry%DF'
690
+
691
+ :param uri: The URI to convert.
692
+ :param charset: The encoding to encode unquoted bytes with.
693
+ :param errors: Error handler to use during ``bytes.encode``. By
694
+ default, invalid bytes are left quoted.
695
+
696
+ .. versionchanged:: 0.15
697
+ All reserved and invalid characters remain quoted. Previously,
698
+ only some reserved characters were preserved, and invalid bytes
699
+ were replaced instead of left quoted.
700
+
701
+ .. versionadded:: 0.6
702
+ """
703
+ if isinstance(uri, tuple):
704
+ uri = url_unparse(uri)
705
+
706
+ uri = url_parse(to_unicode(uri, charset))
707
+ path = url_unquote(uri.path, charset, errors, _to_iri_unsafe)
708
+ query = url_unquote(uri.query, charset, errors, _to_iri_unsafe)
709
+ fragment = url_unquote(uri.fragment, charset, errors, _to_iri_unsafe)
710
+ return url_unparse((uri.scheme, uri.decode_netloc(), path, query, fragment))
711
+
712
+
713
+ # reserved characters remain unquoted when quoting to URI
714
+ _to_uri_safe = ":/?#[]@!$&'()*+,;=%"
715
+
716
+
717
+ def iri_to_uri(iri, charset="utf-8", errors="strict", safe_conversion=False):
718
+ """Convert an IRI to a URI. All non-ASCII and unsafe characters are
719
+ quoted. If the URL has a domain, it is encoded to Punycode.
720
+
721
+ >>> iri_to_uri('http://\\u2603.net/p\\xe5th?q=\\xe8ry%DF')
722
+ 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF'
723
+
724
+ :param iri: The IRI to convert.
725
+ :param charset: The encoding of the IRI.
726
+ :param errors: Error handler to use during ``bytes.encode``.
727
+ :param safe_conversion: Return the URL unchanged if it only contains
728
+ ASCII characters and no whitespace. See the explanation below.
729
+
730
+ There is a general problem with IRI conversion with some protocols
731
+ that are in violation of the URI specification. Consider the
732
+ following two IRIs::
733
+
734
+ magnet:?xt=uri:whatever
735
+ itms-services://?action=download-manifest
736
+
737
+ After parsing, we don't know if the scheme requires the ``//``,
738
+ which is dropped if empty, but conveys different meanings in the
739
+ final URL if it's present or not. In this case, you can use
740
+ ``safe_conversion``, which will return the URL unchanged if it only
741
+ contains ASCII characters and no whitespace. This can result in a
742
+ URI with unquoted characters if it was not already quoted correctly,
743
+ but preserves the URL's semantics. Werkzeug uses this for the
744
+ ``Location`` header for redirects.
745
+
746
+ .. versionchanged:: 0.15
747
+ All reserved characters remain unquoted. Previously, only some
748
+ reserved characters were left unquoted.
749
+
750
+ .. versionchanged:: 0.9.6
751
+ The ``safe_conversion`` parameter was added.
752
+
753
+ .. versionadded:: 0.6
754
+ """
755
+ if isinstance(iri, tuple):
756
+ iri = url_unparse(iri)
757
+
758
+ if safe_conversion:
759
+ # If we're not sure if it's safe to convert the URL, and it only
760
+ # contains ASCII characters, return it unconverted.
761
+ try:
762
+ native_iri = to_native(iri)
763
+ ascii_iri = native_iri.encode("ascii")
764
+
765
+ # Only return if it doesn't have whitespace. (Why?)
766
+ if len(ascii_iri.split()) == 1:
767
+ return native_iri
768
+ except UnicodeError:
769
+ pass
770
+
771
+ iri = url_parse(to_unicode(iri, charset, errors))
772
+ path = url_quote(iri.path, charset, errors, _to_uri_safe)
773
+ query = url_quote(iri.query, charset, errors, _to_uri_safe)
774
+ fragment = url_quote(iri.fragment, charset, errors, _to_uri_safe)
775
+ return to_native(
776
+ url_unparse((iri.scheme, iri.encode_netloc(), path, query, fragment))
777
+ )
778
+
779
+
780
+ def url_decode(
781
+ s,
782
+ charset="utf-8",
783
+ decode_keys=False,
784
+ include_empty=True,
785
+ errors="replace",
786
+ separator="&",
787
+ cls=None,
788
+ ):
789
+ """
790
+ Parse a querystring and return it as :class:`MultiDict`. There is a
791
+ difference in key decoding on different Python versions. On Python 3
792
+ keys will always be fully decoded whereas on Python 2, keys will
793
+ remain bytestrings if they fit into ASCII. On 2.x keys can be forced
794
+ to be unicode by setting `decode_keys` to `True`.
795
+
796
+ If the charset is set to `None` no unicode decoding will happen and
797
+ raw bytes will be returned.
798
+
799
+ Per default a missing value for a key will default to an empty key. If
800
+ you don't want that behavior you can set `include_empty` to `False`.
801
+
802
+ Per default encoding errors are ignored. If you want a different behavior
803
+ you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
804
+ `HTTPUnicodeError` is raised.
805
+
806
+ .. versionchanged:: 0.5
807
+ In previous versions ";" and "&" could be used for url decoding.
808
+ This changed in 0.5 where only "&" is supported. If you want to
809
+ use ";" instead a different `separator` can be provided.
810
+
811
+ The `cls` parameter was added.
812
+
813
+ :param s: a string with the query string to decode.
814
+ :param charset: the charset of the query string. If set to `None`
815
+ no unicode decoding will take place.
816
+ :param decode_keys: Used on Python 2.x to control whether keys should
817
+ be forced to be unicode objects. If set to `True`
818
+ then keys will be unicode in all cases. Otherwise,
819
+ they remain `str` if they fit into ASCII.
820
+ :param include_empty: Set to `False` if you don't want empty values to
821
+ appear in the dict.
822
+ :param errors: the decoding error behavior.
823
+ :param separator: the pair separator to be used, defaults to ``&``
824
+ :param cls: an optional dict class to use. If this is not specified
825
+ or `None` the default :class:`MultiDict` is used.
826
+ """
827
+ if cls is None:
828
+ from .datastructures import MultiDict
829
+
830
+ cls = MultiDict
831
+ if isinstance(s, text_type) and not isinstance(separator, text_type):
832
+ separator = separator.decode(charset or "ascii")
833
+ elif isinstance(s, bytes) and not isinstance(separator, bytes):
834
+ separator = separator.encode(charset or "ascii")
835
+ return cls(
836
+ _url_decode_impl(
837
+ s.split(separator), charset, decode_keys, include_empty, errors
838
+ )
839
+ )
840
+
841
+
842
+ def url_decode_stream(
843
+ stream,
844
+ charset="utf-8",
845
+ decode_keys=False,
846
+ include_empty=True,
847
+ errors="replace",
848
+ separator="&",
849
+ cls=None,
850
+ limit=None,
851
+ return_iterator=False,
852
+ ):
853
+ """Works like :func:`url_decode` but decodes a stream. The behavior
854
+ of stream and limit follows functions like
855
+ :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is
856
+ directly fed to the `cls` so you can consume the data while it's
857
+ parsed.
858
+
859
+ .. versionadded:: 0.8
860
+
861
+ :param stream: a stream with the encoded querystring
862
+ :param charset: the charset of the query string. If set to `None`
863
+ no unicode decoding will take place.
864
+ :param decode_keys: Used on Python 2.x to control whether keys should
865
+ be forced to be unicode objects. If set to `True`,
866
+ keys will be unicode in all cases. Otherwise, they
867
+ remain `str` if they fit into ASCII.
868
+ :param include_empty: Set to `False` if you don't want empty values to
869
+ appear in the dict.
870
+ :param errors: the decoding error behavior.
871
+ :param separator: the pair separator to be used, defaults to ``&``
872
+ :param cls: an optional dict class to use. If this is not specified
873
+ or `None` the default :class:`MultiDict` is used.
874
+ :param limit: the content length of the URL data. Not necessary if
875
+ a limited stream is provided.
876
+ :param return_iterator: if set to `True` the `cls` argument is ignored
877
+ and an iterator over all decoded pairs is
878
+ returned
879
+ """
880
+ from .wsgi import make_chunk_iter
881
+
882
+ pair_iter = make_chunk_iter(stream, separator, limit)
883
+ decoder = _url_decode_impl(pair_iter, charset, decode_keys, include_empty, errors)
884
+
885
+ if return_iterator:
886
+ return decoder
887
+
888
+ if cls is None:
889
+ from .datastructures import MultiDict
890
+
891
+ cls = MultiDict
892
+
893
+ return cls(decoder)
894
+
895
+
896
+ def _url_decode_impl(pair_iter, charset, decode_keys, include_empty, errors):
897
+ for pair in pair_iter:
898
+ if not pair:
899
+ continue
900
+ s = make_literal_wrapper(pair)
901
+ equal = s("=")
902
+ if equal in pair:
903
+ key, value = pair.split(equal, 1)
904
+ else:
905
+ if not include_empty:
906
+ continue
907
+ key = pair
908
+ value = s("")
909
+ key = url_unquote_plus(key, charset, errors)
910
+ if charset is not None and PY2 and not decode_keys:
911
+ key = try_coerce_native(key)
912
+ yield key, url_unquote_plus(value, charset, errors)
913
+
914
+
915
+ def url_encode(
916
+ obj, charset="utf-8", encode_keys=False, sort=False, key=None, separator=b"&"
917
+ ):
918
+ """URL encode a dict/`MultiDict`. If a value is `None` it will not appear
919
+ in the result string. Per default only values are encoded into the target
920
+ charset strings. If `encode_keys` is set to ``True`` unicode keys are
921
+ supported too.
922
+
923
+ If `sort` is set to `True` the items are sorted by `key` or the default
924
+ sorting algorithm.
925
+
926
+ .. versionadded:: 0.5
927
+ `sort`, `key`, and `separator` were added.
928
+
929
+ :param obj: the object to encode into a query string.
930
+ :param charset: the charset of the query string.
931
+ :param encode_keys: set to `True` if you have unicode keys. (Ignored on
932
+ Python 3.x)
933
+ :param sort: set to `True` if you want parameters to be sorted by `key`.
934
+ :param separator: the separator to be used for the pairs.
935
+ :param key: an optional function to be used for sorting. For more details
936
+ check out the :func:`sorted` documentation.
937
+ """
938
+ separator = to_native(separator, "ascii")
939
+ return separator.join(_url_encode_impl(obj, charset, encode_keys, sort, key))
940
+
941
+
942
+ def url_encode_stream(
943
+ obj,
944
+ stream=None,
945
+ charset="utf-8",
946
+ encode_keys=False,
947
+ sort=False,
948
+ key=None,
949
+ separator=b"&",
950
+ ):
951
+ """Like :meth:`url_encode` but writes the results to a stream
952
+ object. If the stream is `None` a generator over all encoded
953
+ pairs is returned.
954
+
955
+ .. versionadded:: 0.8
956
+
957
+ :param obj: the object to encode into a query string.
958
+ :param stream: a stream to write the encoded object into or `None` if
959
+ an iterator over the encoded pairs should be returned. In
960
+ that case the separator argument is ignored.
961
+ :param charset: the charset of the query string.
962
+ :param encode_keys: set to `True` if you have unicode keys. (Ignored on
963
+ Python 3.x)
964
+ :param sort: set to `True` if you want parameters to be sorted by `key`.
965
+ :param separator: the separator to be used for the pairs.
966
+ :param key: an optional function to be used for sorting. For more details
967
+ check out the :func:`sorted` documentation.
968
+ """
969
+ separator = to_native(separator, "ascii")
970
+ gen = _url_encode_impl(obj, charset, encode_keys, sort, key)
971
+ if stream is None:
972
+ return gen
973
+ for idx, chunk in enumerate(gen):
974
+ if idx:
975
+ stream.write(separator)
976
+ stream.write(chunk)
977
+
978
+
979
+ def url_join(base, url, allow_fragments=True):
980
+ """Join a base URL and a possibly relative URL to form an absolute
981
+ interpretation of the latter.
982
+
983
+ :param base: the base URL for the join operation.
984
+ :param url: the URL to join.
985
+ :param allow_fragments: indicates whether fragments should be allowed.
986
+ """
987
+ if isinstance(base, tuple):
988
+ base = url_unparse(base)
989
+ if isinstance(url, tuple):
990
+ url = url_unparse(url)
991
+
992
+ base, url = normalize_string_tuple((base, url))
993
+ s = make_literal_wrapper(base)
994
+
995
+ if not base:
996
+ return url
997
+ if not url:
998
+ return base
999
+
1000
+ bscheme, bnetloc, bpath, bquery, bfragment = url_parse(
1001
+ base, allow_fragments=allow_fragments
1002
+ )
1003
+ scheme, netloc, path, query, fragment = url_parse(url, bscheme, allow_fragments)
1004
+ if scheme != bscheme:
1005
+ return url
1006
+ if netloc:
1007
+ return url_unparse((scheme, netloc, path, query, fragment))
1008
+ netloc = bnetloc
1009
+
1010
+ if path[:1] == s("/"):
1011
+ segments = path.split(s("/"))
1012
+ elif not path:
1013
+ segments = bpath.split(s("/"))
1014
+ if not query:
1015
+ query = bquery
1016
+ else:
1017
+ segments = bpath.split(s("/"))[:-1] + path.split(s("/"))
1018
+
1019
+ # If the rightmost part is "./" we want to keep the slash but
1020
+ # remove the dot.
1021
+ if segments[-1] == s("."):
1022
+ segments[-1] = s("")
1023
+
1024
+ # Resolve ".." and "."
1025
+ segments = [segment for segment in segments if segment != s(".")]
1026
+ while 1:
1027
+ i = 1
1028
+ n = len(segments) - 1
1029
+ while i < n:
1030
+ if segments[i] == s("..") and segments[i - 1] not in (s(""), s("..")):
1031
+ del segments[i - 1 : i + 1]
1032
+ break
1033
+ i += 1
1034
+ else:
1035
+ break
1036
+
1037
+ # Remove trailing ".." if the URL is absolute
1038
+ unwanted_marker = [s(""), s("..")]
1039
+ while segments[:2] == unwanted_marker:
1040
+ del segments[1]
1041
+
1042
+ path = s("/").join(segments)
1043
+ return url_unparse((scheme, netloc, path, query, fragment))
1044
+
1045
+
1046
+ class Href(object):
1047
+ """Implements a callable that constructs URLs with the given base. The
1048
+ function can be called with any number of positional and keyword
1049
+ arguments which than are used to assemble the URL. Works with URLs
1050
+ and posix paths.
1051
+
1052
+ Positional arguments are appended as individual segments to
1053
+ the path of the URL:
1054
+
1055
+ >>> href = Href('/foo')
1056
+ >>> href('bar', 23)
1057
+ '/foo/bar/23'
1058
+ >>> href('foo', bar=23)
1059
+ '/foo/foo?bar=23'
1060
+
1061
+ If any of the arguments (positional or keyword) evaluates to `None` it
1062
+ will be skipped. If no keyword arguments are given the last argument
1063
+ can be a :class:`dict` or :class:`MultiDict` (or any other dict subclass),
1064
+ otherwise the keyword arguments are used for the query parameters, cutting
1065
+ off the first trailing underscore of the parameter name:
1066
+
1067
+ >>> href(is_=42)
1068
+ '/foo?is=42'
1069
+ >>> href({'foo': 'bar'})
1070
+ '/foo?foo=bar'
1071
+
1072
+ Combining of both methods is not allowed:
1073
+
1074
+ >>> href({'foo': 'bar'}, bar=42)
1075
+ Traceback (most recent call last):
1076
+ ...
1077
+ TypeError: keyword arguments and query-dicts can't be combined
1078
+
1079
+ Accessing attributes on the href object creates a new href object with
1080
+ the attribute name as prefix:
1081
+
1082
+ >>> bar_href = href.bar
1083
+ >>> bar_href("blub")
1084
+ '/foo/bar/blub'
1085
+
1086
+ If `sort` is set to `True` the items are sorted by `key` or the default
1087
+ sorting algorithm:
1088
+
1089
+ >>> href = Href("/", sort=True)
1090
+ >>> href(a=1, b=2, c=3)
1091
+ '/?a=1&b=2&c=3'
1092
+
1093
+ .. versionadded:: 0.5
1094
+ `sort` and `key` were added.
1095
+ """
1096
+
1097
+ def __init__(self, base="./", charset="utf-8", sort=False, key=None):
1098
+ if not base:
1099
+ base = "./"
1100
+ self.base = base
1101
+ self.charset = charset
1102
+ self.sort = sort
1103
+ self.key = key
1104
+
1105
+ def __getattr__(self, name):
1106
+ if name[:2] == "__":
1107
+ raise AttributeError(name)
1108
+ base = self.base
1109
+ if base[-1:] != "/":
1110
+ base += "/"
1111
+ return Href(url_join(base, name), self.charset, self.sort, self.key)
1112
+
1113
+ def __call__(self, *path, **query):
1114
+ if path and isinstance(path[-1], dict):
1115
+ if query:
1116
+ raise TypeError("keyword arguments and query-dicts can't be combined")
1117
+ query, path = path[-1], path[:-1]
1118
+ elif query:
1119
+ query = dict(
1120
+ [(k.endswith("_") and k[:-1] or k, v) for k, v in query.items()]
1121
+ )
1122
+ path = "/".join(
1123
+ [
1124
+ to_unicode(url_quote(x, self.charset), "ascii")
1125
+ for x in path
1126
+ if x is not None
1127
+ ]
1128
+ ).lstrip("/")
1129
+ rv = self.base
1130
+ if path:
1131
+ if not rv.endswith("/"):
1132
+ rv += "/"
1133
+ rv = url_join(rv, "./" + path)
1134
+ if query:
1135
+ rv += "?" + to_unicode(
1136
+ url_encode(query, self.charset, sort=self.sort, key=self.key), "ascii"
1137
+ )
1138
+ return to_native(rv)