plain 0.1.0__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 (169) hide show
  1. plain/README.md +33 -0
  2. plain/__main__.py +5 -0
  3. plain/assets/README.md +56 -0
  4. plain/assets/__init__.py +6 -0
  5. plain/assets/finders.py +233 -0
  6. plain/assets/preflight.py +14 -0
  7. plain/assets/storage.py +916 -0
  8. plain/assets/utils.py +52 -0
  9. plain/assets/whitenoise/__init__.py +5 -0
  10. plain/assets/whitenoise/base.py +259 -0
  11. plain/assets/whitenoise/compress.py +189 -0
  12. plain/assets/whitenoise/media_types.py +137 -0
  13. plain/assets/whitenoise/middleware.py +197 -0
  14. plain/assets/whitenoise/responders.py +286 -0
  15. plain/assets/whitenoise/storage.py +178 -0
  16. plain/assets/whitenoise/string_utils.py +13 -0
  17. plain/cli/README.md +123 -0
  18. plain/cli/__init__.py +3 -0
  19. plain/cli/cli.py +439 -0
  20. plain/cli/formatting.py +61 -0
  21. plain/cli/packages.py +73 -0
  22. plain/cli/print.py +9 -0
  23. plain/cli/startup.py +33 -0
  24. plain/csrf/README.md +3 -0
  25. plain/csrf/middleware.py +466 -0
  26. plain/csrf/views.py +10 -0
  27. plain/debug.py +23 -0
  28. plain/exceptions.py +242 -0
  29. plain/forms/README.md +14 -0
  30. plain/forms/__init__.py +8 -0
  31. plain/forms/boundfield.py +58 -0
  32. plain/forms/exceptions.py +11 -0
  33. plain/forms/fields.py +1030 -0
  34. plain/forms/forms.py +297 -0
  35. plain/http/README.md +1 -0
  36. plain/http/__init__.py +51 -0
  37. plain/http/cookie.py +20 -0
  38. plain/http/multipartparser.py +743 -0
  39. plain/http/request.py +754 -0
  40. plain/http/response.py +719 -0
  41. plain/internal/__init__.py +0 -0
  42. plain/internal/files/README.md +3 -0
  43. plain/internal/files/__init__.py +3 -0
  44. plain/internal/files/base.py +161 -0
  45. plain/internal/files/locks.py +127 -0
  46. plain/internal/files/move.py +102 -0
  47. plain/internal/files/temp.py +79 -0
  48. plain/internal/files/uploadedfile.py +150 -0
  49. plain/internal/files/uploadhandler.py +254 -0
  50. plain/internal/files/utils.py +78 -0
  51. plain/internal/handlers/__init__.py +0 -0
  52. plain/internal/handlers/base.py +133 -0
  53. plain/internal/handlers/exception.py +145 -0
  54. plain/internal/handlers/wsgi.py +216 -0
  55. plain/internal/legacy/__init__.py +0 -0
  56. plain/internal/legacy/__main__.py +12 -0
  57. plain/internal/legacy/management/__init__.py +414 -0
  58. plain/internal/legacy/management/base.py +692 -0
  59. plain/internal/legacy/management/color.py +113 -0
  60. plain/internal/legacy/management/commands/__init__.py +0 -0
  61. plain/internal/legacy/management/commands/collectstatic.py +297 -0
  62. plain/internal/legacy/management/sql.py +67 -0
  63. plain/internal/legacy/management/utils.py +175 -0
  64. plain/json.py +40 -0
  65. plain/logs/README.md +24 -0
  66. plain/logs/__init__.py +5 -0
  67. plain/logs/configure.py +39 -0
  68. plain/logs/loggers.py +74 -0
  69. plain/logs/utils.py +46 -0
  70. plain/middleware/README.md +3 -0
  71. plain/middleware/__init__.py +0 -0
  72. plain/middleware/clickjacking.py +52 -0
  73. plain/middleware/common.py +87 -0
  74. plain/middleware/gzip.py +64 -0
  75. plain/middleware/security.py +64 -0
  76. plain/packages/README.md +41 -0
  77. plain/packages/__init__.py +4 -0
  78. plain/packages/config.py +259 -0
  79. plain/packages/registry.py +438 -0
  80. plain/paginator.py +187 -0
  81. plain/preflight/README.md +3 -0
  82. plain/preflight/__init__.py +38 -0
  83. plain/preflight/compatibility/__init__.py +0 -0
  84. plain/preflight/compatibility/django_4_0.py +20 -0
  85. plain/preflight/files.py +19 -0
  86. plain/preflight/messages.py +88 -0
  87. plain/preflight/registry.py +72 -0
  88. plain/preflight/security/__init__.py +0 -0
  89. plain/preflight/security/base.py +268 -0
  90. plain/preflight/security/csrf.py +40 -0
  91. plain/preflight/urls.py +117 -0
  92. plain/runtime/README.md +75 -0
  93. plain/runtime/__init__.py +61 -0
  94. plain/runtime/global_settings.py +199 -0
  95. plain/runtime/user_settings.py +353 -0
  96. plain/signals/README.md +14 -0
  97. plain/signals/__init__.py +5 -0
  98. plain/signals/dispatch/__init__.py +9 -0
  99. plain/signals/dispatch/dispatcher.py +320 -0
  100. plain/signals/dispatch/license.txt +35 -0
  101. plain/signing.py +299 -0
  102. plain/templates/README.md +20 -0
  103. plain/templates/__init__.py +6 -0
  104. plain/templates/core.py +24 -0
  105. plain/templates/jinja/README.md +227 -0
  106. plain/templates/jinja/__init__.py +22 -0
  107. plain/templates/jinja/defaults.py +119 -0
  108. plain/templates/jinja/extensions.py +39 -0
  109. plain/templates/jinja/filters.py +28 -0
  110. plain/templates/jinja/globals.py +19 -0
  111. plain/test/README.md +3 -0
  112. plain/test/__init__.py +16 -0
  113. plain/test/client.py +985 -0
  114. plain/test/utils.py +255 -0
  115. plain/urls/README.md +3 -0
  116. plain/urls/__init__.py +40 -0
  117. plain/urls/base.py +118 -0
  118. plain/urls/conf.py +94 -0
  119. plain/urls/converters.py +66 -0
  120. plain/urls/exceptions.py +9 -0
  121. plain/urls/resolvers.py +731 -0
  122. plain/utils/README.md +3 -0
  123. plain/utils/__init__.py +0 -0
  124. plain/utils/_os.py +52 -0
  125. plain/utils/cache.py +327 -0
  126. plain/utils/connection.py +84 -0
  127. plain/utils/crypto.py +76 -0
  128. plain/utils/datastructures.py +345 -0
  129. plain/utils/dateformat.py +329 -0
  130. plain/utils/dateparse.py +154 -0
  131. plain/utils/dates.py +76 -0
  132. plain/utils/deconstruct.py +54 -0
  133. plain/utils/decorators.py +90 -0
  134. plain/utils/deprecation.py +6 -0
  135. plain/utils/duration.py +44 -0
  136. plain/utils/email.py +12 -0
  137. plain/utils/encoding.py +235 -0
  138. plain/utils/functional.py +456 -0
  139. plain/utils/hashable.py +26 -0
  140. plain/utils/html.py +401 -0
  141. plain/utils/http.py +374 -0
  142. plain/utils/inspect.py +73 -0
  143. plain/utils/ipv6.py +46 -0
  144. plain/utils/itercompat.py +8 -0
  145. plain/utils/module_loading.py +69 -0
  146. plain/utils/regex_helper.py +353 -0
  147. plain/utils/safestring.py +72 -0
  148. plain/utils/termcolors.py +221 -0
  149. plain/utils/text.py +518 -0
  150. plain/utils/timesince.py +138 -0
  151. plain/utils/timezone.py +244 -0
  152. plain/utils/tree.py +126 -0
  153. plain/validators.py +603 -0
  154. plain/views/README.md +268 -0
  155. plain/views/__init__.py +18 -0
  156. plain/views/base.py +107 -0
  157. plain/views/csrf.py +24 -0
  158. plain/views/errors.py +25 -0
  159. plain/views/exceptions.py +4 -0
  160. plain/views/forms.py +76 -0
  161. plain/views/objects.py +229 -0
  162. plain/views/redirect.py +72 -0
  163. plain/views/templates.py +66 -0
  164. plain/wsgi.py +11 -0
  165. plain-0.1.0.dist-info/LICENSE +85 -0
  166. plain-0.1.0.dist-info/METADATA +51 -0
  167. plain-0.1.0.dist-info/RECORD +169 -0
  168. plain-0.1.0.dist-info/WHEEL +4 -0
  169. plain-0.1.0.dist-info/entry_points.txt +3 -0
plain/utils/http.py ADDED
@@ -0,0 +1,374 @@
1
+ import base64
2
+ import datetime
3
+ import re
4
+ import unicodedata
5
+ from binascii import Error as BinasciiError
6
+ from email.utils import formatdate
7
+ from urllib.parse import quote, unquote, urlparse
8
+ from urllib.parse import urlencode as original_urlencode
9
+
10
+ from plain.utils.datastructures import MultiValueDict
11
+ from plain.utils.regex_helper import _lazy_re_compile
12
+
13
+ # Based on RFC 9110 Appendix A.
14
+ ETAG_MATCH = _lazy_re_compile(
15
+ r"""
16
+ \A( # start of string and capture group
17
+ (?:W/)? # optional weak indicator
18
+ " # opening quote
19
+ [^"]* # any sequence of non-quote characters
20
+ " # end quote
21
+ )\Z # end of string and capture group
22
+ """,
23
+ re.X,
24
+ )
25
+
26
+ MONTHS = "jan feb mar apr may jun jul aug sep oct nov dec".split()
27
+ __D = r"(?P<day>[0-9]{2})"
28
+ __D2 = r"(?P<day>[ 0-9][0-9])"
29
+ __M = r"(?P<mon>\w{3})"
30
+ __Y = r"(?P<year>[0-9]{4})"
31
+ __Y2 = r"(?P<year>[0-9]{2})"
32
+ __T = r"(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2})"
33
+ RFC1123_DATE = _lazy_re_compile(rf"^\w{{3}}, {__D} {__M} {__Y} {__T} GMT$")
34
+ RFC850_DATE = _lazy_re_compile(rf"^\w{{6,9}}, {__D}-{__M}-{__Y2} {__T} GMT$")
35
+ ASCTIME_DATE = _lazy_re_compile(rf"^\w{{3}} {__M} {__D2} {__T} {__Y}$")
36
+
37
+ RFC3986_GENDELIMS = ":/?#[]@"
38
+ RFC3986_SUBDELIMS = "!$&'()*+,;="
39
+
40
+
41
+ def urlencode(query, doseq=False):
42
+ """
43
+ A version of Python's urllib.parse.urlencode() function that can operate on
44
+ MultiValueDict and non-string values.
45
+ """
46
+ if isinstance(query, MultiValueDict):
47
+ query = query.lists()
48
+ elif hasattr(query, "items"):
49
+ query = query.items()
50
+ query_params = []
51
+ for key, value in query:
52
+ if value is None:
53
+ raise TypeError(
54
+ "Cannot encode None for key '%s' in a query string. Did you "
55
+ "mean to pass an empty string or omit the value?" % key
56
+ )
57
+ elif not doseq or isinstance(value, str | bytes):
58
+ query_val = value
59
+ else:
60
+ try:
61
+ itr = iter(value)
62
+ except TypeError:
63
+ query_val = value
64
+ else:
65
+ # Consume generators and iterators, when doseq=True, to
66
+ # work around https://bugs.python.org/issue31706.
67
+ query_val = []
68
+ for item in itr:
69
+ if item is None:
70
+ raise TypeError(
71
+ "Cannot encode None for key '%s' in a query "
72
+ "string. Did you mean to pass an empty string or "
73
+ "omit the value?" % key
74
+ )
75
+ elif not isinstance(item, bytes):
76
+ item = str(item)
77
+ query_val.append(item)
78
+ query_params.append((key, query_val))
79
+ return original_urlencode(query_params, doseq)
80
+
81
+
82
+ def http_date(epoch_seconds=None):
83
+ """
84
+ Format the time to match the RFC 5322 date format as specified by RFC 9110
85
+ Section 5.6.7.
86
+
87
+ `epoch_seconds` is a floating point number expressed in seconds since the
88
+ epoch, in UTC - such as that outputted by time.time(). If set to None, it
89
+ defaults to the current time.
90
+
91
+ Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
92
+ """
93
+ return formatdate(epoch_seconds, usegmt=True)
94
+
95
+
96
+ def parse_http_date(date):
97
+ """
98
+ Parse a date format as specified by HTTP RFC 9110 Section 5.6.7.
99
+
100
+ The three formats allowed by the RFC are accepted, even if only the first
101
+ one is still in widespread use.
102
+
103
+ Return an integer expressed in seconds since the epoch, in UTC.
104
+ """
105
+ # email.utils.parsedate() does the job for RFC 1123 dates; unfortunately
106
+ # RFC 9110 makes it mandatory to support RFC 850 dates too. So we roll
107
+ # our own RFC-compliant parsing.
108
+ for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
109
+ m = regex.match(date)
110
+ if m is not None:
111
+ break
112
+ else:
113
+ raise ValueError("%r is not in a valid HTTP date format" % date)
114
+ try:
115
+ tz = datetime.timezone.utc
116
+ year = int(m["year"])
117
+ if year < 100:
118
+ current_year = datetime.datetime.now(tz=tz).year
119
+ current_century = current_year - (current_year % 100)
120
+ if year - (current_year % 100) > 50:
121
+ # year that appears to be more than 50 years in the future are
122
+ # interpreted as representing the past.
123
+ year += current_century - 100
124
+ else:
125
+ year += current_century
126
+ month = MONTHS.index(m["mon"].lower()) + 1
127
+ day = int(m["day"])
128
+ hour = int(m["hour"])
129
+ min = int(m["min"])
130
+ sec = int(m["sec"])
131
+ result = datetime.datetime(year, month, day, hour, min, sec, tzinfo=tz)
132
+ return int(result.timestamp())
133
+ except Exception as exc:
134
+ raise ValueError("%r is not a valid date" % date) from exc
135
+
136
+
137
+ def parse_http_date_safe(date):
138
+ """
139
+ Same as parse_http_date, but return None if the input is invalid.
140
+ """
141
+ try:
142
+ return parse_http_date(date)
143
+ except Exception:
144
+ pass
145
+
146
+
147
+ # Base 36 functions: useful for generating compact URLs
148
+
149
+
150
+ def base36_to_int(s):
151
+ """
152
+ Convert a base 36 string to an int. Raise ValueError if the input won't fit
153
+ into an int.
154
+ """
155
+ # To prevent overconsumption of server resources, reject any
156
+ # base36 string that is longer than 13 base36 digits (13 digits
157
+ # is sufficient to base36-encode any 64-bit integer)
158
+ if len(s) > 13:
159
+ raise ValueError("Base36 input too large")
160
+ return int(s, 36)
161
+
162
+
163
+ def int_to_base36(i):
164
+ """Convert an integer to a base36 string."""
165
+ char_set = "0123456789abcdefghijklmnopqrstuvwxyz"
166
+ if i < 0:
167
+ raise ValueError("Negative base36 conversion input.")
168
+ if i < 36:
169
+ return char_set[i]
170
+ b36 = ""
171
+ while i != 0:
172
+ i, n = divmod(i, 36)
173
+ b36 = char_set[n] + b36
174
+ return b36
175
+
176
+
177
+ def urlsafe_base64_encode(s):
178
+ """
179
+ Encode a bytestring to a base64 string for use in URLs. Strip any trailing
180
+ equal signs.
181
+ """
182
+ return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii")
183
+
184
+
185
+ def urlsafe_base64_decode(s):
186
+ """
187
+ Decode a base64 encoded string. Add back any trailing equal signs that
188
+ might have been stripped.
189
+ """
190
+ s = s.encode()
191
+ try:
192
+ return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"="))
193
+ except (LookupError, BinasciiError) as e:
194
+ raise ValueError(e)
195
+
196
+
197
+ def parse_etags(etag_str):
198
+ """
199
+ Parse a string of ETags given in an If-None-Match or If-Match header as
200
+ defined by RFC 9110. Return a list of quoted ETags, or ['*'] if all ETags
201
+ should be matched.
202
+ """
203
+ if etag_str.strip() == "*":
204
+ return ["*"]
205
+ else:
206
+ # Parse each ETag individually, and return any that are valid.
207
+ etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(","))
208
+ return [match[1] for match in etag_matches if match]
209
+
210
+
211
+ def quote_etag(etag_str):
212
+ """
213
+ If the provided string is already a quoted ETag, return it. Otherwise, wrap
214
+ the string in quotes, making it a strong ETag.
215
+ """
216
+ if ETAG_MATCH.match(etag_str):
217
+ return etag_str
218
+ else:
219
+ return '"%s"' % etag_str
220
+
221
+
222
+ def is_same_domain(host, pattern):
223
+ """
224
+ Return ``True`` if the host is either an exact match or a match
225
+ to the wildcard pattern.
226
+
227
+ Any pattern beginning with a period matches a domain and all of its
228
+ subdomains. (e.g. ``.example.com`` matches ``example.com`` and
229
+ ``foo.example.com``). Anything else is an exact string match.
230
+ """
231
+ if not pattern:
232
+ return False
233
+
234
+ pattern = pattern.lower()
235
+ return (
236
+ pattern[0] == "."
237
+ and (host.endswith(pattern) or host == pattern[1:])
238
+ or pattern == host
239
+ )
240
+
241
+
242
+ def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
243
+ """
244
+ Return ``True`` if the url uses an allowed host and a safe scheme.
245
+
246
+ Always return ``False`` on an empty url.
247
+
248
+ If ``require_https`` is ``True``, only 'https' will be considered a valid
249
+ scheme, as opposed to 'http' and 'https' with the default, ``False``.
250
+
251
+ Note: "True" doesn't entail that a URL is "safe". It may still be e.g.
252
+ quoted incorrectly. Ensure to also use plain.utils.encoding.iri_to_uri()
253
+ on the path component of untrusted URLs.
254
+ """
255
+ if url is not None:
256
+ url = url.strip()
257
+ if not url:
258
+ return False
259
+ if allowed_hosts is None:
260
+ allowed_hosts = set()
261
+ elif isinstance(allowed_hosts, str):
262
+ allowed_hosts = {allowed_hosts}
263
+ # Chrome treats \ completely as / in paths but it could be part of some
264
+ # basic auth credentials so we need to check both URLs.
265
+ return _url_has_allowed_host_and_scheme(
266
+ url, allowed_hosts, require_https=require_https
267
+ ) and _url_has_allowed_host_and_scheme(
268
+ url.replace("\\", "/"), allowed_hosts, require_https=require_https
269
+ )
270
+
271
+
272
+ def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
273
+ # Chrome considers any URL with more than two slashes to be absolute, but
274
+ # urlparse is not so flexible. Treat any url with three slashes as unsafe.
275
+ if url.startswith("///"):
276
+ return False
277
+ try:
278
+ url_info = urlparse(url)
279
+ except ValueError: # e.g. invalid IPv6 addresses
280
+ return False
281
+ # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
282
+ # In that URL, example.com is not the hostname but, a path component. However,
283
+ # Chrome will still consider example.com to be the hostname, so we must not
284
+ # allow this syntax.
285
+ if not url_info.netloc and url_info.scheme:
286
+ return False
287
+ # Forbid URLs that start with control characters. Some browsers (like
288
+ # Chrome) ignore quite a few control characters at the start of a
289
+ # URL and might consider the URL as scheme relative.
290
+ if unicodedata.category(url[0])[0] == "C":
291
+ return False
292
+ scheme = url_info.scheme
293
+ # Consider URLs without a scheme (e.g. //example.com/p) to be http.
294
+ if not url_info.scheme and url_info.netloc:
295
+ scheme = "http"
296
+ valid_schemes = ["https"] if require_https else ["http", "https"]
297
+ return (not url_info.netloc or url_info.netloc in allowed_hosts) and (
298
+ not scheme or scheme in valid_schemes
299
+ )
300
+
301
+
302
+ def escape_leading_slashes(url):
303
+ """
304
+ If redirecting to an absolute path (two leading slashes), a slash must be
305
+ escaped to prevent browsers from handling the path as schemaless and
306
+ redirecting to another host.
307
+ """
308
+ if url.startswith("//"):
309
+ url = "/%2F{}".format(url.removeprefix("//"))
310
+ return url
311
+
312
+
313
+ def _parseparam(s):
314
+ while s[:1] == ";":
315
+ s = s[1:]
316
+ end = s.find(";")
317
+ while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
318
+ end = s.find(";", end + 1)
319
+ if end < 0:
320
+ end = len(s)
321
+ f = s[:end]
322
+ yield f.strip()
323
+ s = s[end:]
324
+
325
+
326
+ def parse_header_parameters(line):
327
+ """
328
+ Parse a Content-type like header.
329
+ Return the main content-type and a dictionary of options.
330
+ """
331
+ parts = _parseparam(";" + line)
332
+ key = parts.__next__().lower()
333
+ pdict = {}
334
+ for p in parts:
335
+ i = p.find("=")
336
+ if i >= 0:
337
+ has_encoding = False
338
+ name = p[:i].strip().lower()
339
+ if name.endswith("*"):
340
+ # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext")
341
+ # https://tools.ietf.org/html/rfc2231#section-4
342
+ name = name[:-1]
343
+ if p.count("'") == 2:
344
+ has_encoding = True
345
+ value = p[i + 1 :].strip()
346
+ if len(value) >= 2 and value[0] == value[-1] == '"':
347
+ value = value[1:-1]
348
+ value = value.replace("\\\\", "\\").replace('\\"', '"')
349
+ if has_encoding:
350
+ encoding, lang, value = value.split("'")
351
+ value = unquote(value, encoding=encoding)
352
+ pdict[name] = value
353
+ return key, pdict
354
+
355
+
356
+ def content_disposition_header(as_attachment, filename):
357
+ """
358
+ Construct a Content-Disposition HTTP header value from the given filename
359
+ as specified by RFC 6266.
360
+ """
361
+ if filename:
362
+ disposition = "attachment" if as_attachment else "inline"
363
+ try:
364
+ filename.encode("ascii")
365
+ file_expr = 'filename="{}"'.format(
366
+ filename.replace("\\", "\\\\").replace('"', r"\"")
367
+ )
368
+ except UnicodeEncodeError:
369
+ file_expr = f"filename*=utf-8''{quote(filename)}"
370
+ return f"{disposition}; {file_expr}"
371
+ elif as_attachment:
372
+ return "attachment"
373
+ else:
374
+ return None
plain/utils/inspect.py ADDED
@@ -0,0 +1,73 @@
1
+ import functools
2
+ import inspect
3
+
4
+
5
+ @functools.lru_cache(maxsize=512)
6
+ def _get_func_parameters(func, remove_first):
7
+ parameters = tuple(inspect.signature(func).parameters.values())
8
+ if remove_first:
9
+ parameters = parameters[1:]
10
+ return parameters
11
+
12
+
13
+ def _get_callable_parameters(meth_or_func):
14
+ is_method = inspect.ismethod(meth_or_func)
15
+ func = meth_or_func.__func__ if is_method else meth_or_func
16
+ return _get_func_parameters(func, remove_first=is_method)
17
+
18
+
19
+ def get_func_args(func):
20
+ params = _get_callable_parameters(func)
21
+ return [
22
+ param.name
23
+ for param in params
24
+ if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
25
+ ]
26
+
27
+
28
+ def get_func_full_args(func):
29
+ """
30
+ Return a list of (argument name, default value) tuples. If the argument
31
+ does not have a default value, omit it in the tuple. Arguments such as
32
+ *args and **kwargs are also included.
33
+ """
34
+ params = _get_callable_parameters(func)
35
+ args = []
36
+ for param in params:
37
+ name = param.name
38
+ # Ignore 'self'
39
+ if name == "self":
40
+ continue
41
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
42
+ name = "*" + name
43
+ elif param.kind == inspect.Parameter.VAR_KEYWORD:
44
+ name = "**" + name
45
+ if param.default != inspect.Parameter.empty:
46
+ args.append((name, param.default))
47
+ else:
48
+ args.append((name,))
49
+ return args
50
+
51
+
52
+ def func_accepts_kwargs(func):
53
+ """Return True if function 'func' accepts keyword arguments **kwargs."""
54
+ return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD)
55
+
56
+
57
+ def func_accepts_var_args(func):
58
+ """
59
+ Return True if function 'func' accepts positional arguments *args.
60
+ """
61
+ return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_POSITIONAL)
62
+
63
+
64
+ def method_has_no_args(meth):
65
+ """Return True if a method only accepts 'self'."""
66
+ count = len(
67
+ [p for p in _get_callable_parameters(meth) if p.kind == p.POSITIONAL_OR_KEYWORD]
68
+ )
69
+ return count == 0 if inspect.ismethod(meth) else count == 1
70
+
71
+
72
+ def func_supports_parameter(func, name):
73
+ return any(param.name == name for param in _get_callable_parameters(func))
plain/utils/ipv6.py ADDED
@@ -0,0 +1,46 @@
1
+ import ipaddress
2
+
3
+ from plain.exceptions import ValidationError
4
+
5
+
6
+ def clean_ipv6_address(
7
+ ip_str, unpack_ipv4=False, error_message="This is not a valid IPv6 address."
8
+ ):
9
+ """
10
+ Clean an IPv6 address string.
11
+
12
+ Raise ValidationError if the address is invalid.
13
+
14
+ Replace the longest continuous zero-sequence with "::", remove leading
15
+ zeroes, and make sure all hextets are lowercase.
16
+
17
+ Args:
18
+ ip_str: A valid IPv6 address.
19
+ unpack_ipv4: if an IPv4-mapped address is found,
20
+ return the plain IPv4 address (default=False).
21
+ error_message: An error message used in the ValidationError.
22
+
23
+ Return a compressed IPv6 address or the same value.
24
+ """
25
+ try:
26
+ addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
27
+ except ValueError:
28
+ raise ValidationError(error_message, code="invalid")
29
+
30
+ if unpack_ipv4 and addr.ipv4_mapped:
31
+ return str(addr.ipv4_mapped)
32
+ elif addr.ipv4_mapped:
33
+ return "::ffff:%s" % str(addr.ipv4_mapped)
34
+
35
+ return str(addr)
36
+
37
+
38
+ def is_valid_ipv6_address(ip_str):
39
+ """
40
+ Return whether or not the `ip_str` string is a valid IPv6 address.
41
+ """
42
+ try:
43
+ ipaddress.IPv6Address(ip_str)
44
+ except ValueError:
45
+ return False
46
+ return True
@@ -0,0 +1,8 @@
1
+ def is_iterable(x):
2
+ "An implementation independent way of checking for iterables"
3
+ try:
4
+ iter(x)
5
+ except TypeError:
6
+ return False
7
+ else:
8
+ return True
@@ -0,0 +1,69 @@
1
+ import os
2
+ import sys
3
+ from importlib import import_module
4
+ from importlib.util import find_spec as importlib_find
5
+
6
+
7
+ def cached_import(module_path, class_name):
8
+ # Check whether module is loaded and fully initialized.
9
+ if not (
10
+ (module := sys.modules.get(module_path))
11
+ and (spec := getattr(module, "__spec__", None))
12
+ and getattr(spec, "_initializing", False) is False
13
+ ):
14
+ module = import_module(module_path)
15
+ return getattr(module, class_name)
16
+
17
+
18
+ def import_string(dotted_path):
19
+ """
20
+ Import a dotted module path and return the attribute/class designated by the
21
+ last name in the path. Raise ImportError if the import failed.
22
+ """
23
+ try:
24
+ module_path, class_name = dotted_path.rsplit(".", 1)
25
+ except ValueError as err:
26
+ raise ImportError("%s doesn't look like a module path" % dotted_path) from err
27
+
28
+ try:
29
+ return cached_import(module_path, class_name)
30
+ except AttributeError as err:
31
+ raise ImportError(
32
+ f'Module "{module_path}" does not define a "{class_name}" attribute/class'
33
+ ) from err
34
+
35
+
36
+ def module_has_submodule(package, module_name):
37
+ """See if 'module' is in 'package'."""
38
+ try:
39
+ package_name = package.__name__
40
+ package_path = package.__path__
41
+ except AttributeError:
42
+ # package isn't a package.
43
+ return False
44
+
45
+ full_module_name = package_name + "." + module_name
46
+ try:
47
+ return importlib_find(full_module_name, package_path) is not None
48
+ except ModuleNotFoundError:
49
+ # When module_name is an invalid dotted path, Python raises
50
+ # ModuleNotFoundError.
51
+ return False
52
+
53
+
54
+ def module_dir(module):
55
+ """
56
+ Find the name of the directory that contains a module, if possible.
57
+
58
+ Raise ValueError otherwise, e.g. for namespace packages that are split
59
+ over several directories.
60
+ """
61
+ # Convert to list because __path__ may not support indexing.
62
+ paths = list(getattr(module, "__path__", []))
63
+ if len(paths) == 1:
64
+ return paths[0]
65
+ else:
66
+ filename = getattr(module, "__file__", None)
67
+ if filename is not None:
68
+ return os.path.dirname(filename)
69
+ raise ValueError("Cannot determine directory containing %s" % module)