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.
- plain/README.md +33 -0
- plain/__main__.py +5 -0
- plain/assets/README.md +56 -0
- plain/assets/__init__.py +6 -0
- plain/assets/finders.py +233 -0
- plain/assets/preflight.py +14 -0
- plain/assets/storage.py +916 -0
- plain/assets/utils.py +52 -0
- plain/assets/whitenoise/__init__.py +5 -0
- plain/assets/whitenoise/base.py +259 -0
- plain/assets/whitenoise/compress.py +189 -0
- plain/assets/whitenoise/media_types.py +137 -0
- plain/assets/whitenoise/middleware.py +197 -0
- plain/assets/whitenoise/responders.py +286 -0
- plain/assets/whitenoise/storage.py +178 -0
- plain/assets/whitenoise/string_utils.py +13 -0
- plain/cli/README.md +123 -0
- plain/cli/__init__.py +3 -0
- plain/cli/cli.py +439 -0
- plain/cli/formatting.py +61 -0
- plain/cli/packages.py +73 -0
- plain/cli/print.py +9 -0
- plain/cli/startup.py +33 -0
- plain/csrf/README.md +3 -0
- plain/csrf/middleware.py +466 -0
- plain/csrf/views.py +10 -0
- plain/debug.py +23 -0
- plain/exceptions.py +242 -0
- plain/forms/README.md +14 -0
- plain/forms/__init__.py +8 -0
- plain/forms/boundfield.py +58 -0
- plain/forms/exceptions.py +11 -0
- plain/forms/fields.py +1030 -0
- plain/forms/forms.py +297 -0
- plain/http/README.md +1 -0
- plain/http/__init__.py +51 -0
- plain/http/cookie.py +20 -0
- plain/http/multipartparser.py +743 -0
- plain/http/request.py +754 -0
- plain/http/response.py +719 -0
- plain/internal/__init__.py +0 -0
- plain/internal/files/README.md +3 -0
- plain/internal/files/__init__.py +3 -0
- plain/internal/files/base.py +161 -0
- plain/internal/files/locks.py +127 -0
- plain/internal/files/move.py +102 -0
- plain/internal/files/temp.py +79 -0
- plain/internal/files/uploadedfile.py +150 -0
- plain/internal/files/uploadhandler.py +254 -0
- plain/internal/files/utils.py +78 -0
- plain/internal/handlers/__init__.py +0 -0
- plain/internal/handlers/base.py +133 -0
- plain/internal/handlers/exception.py +145 -0
- plain/internal/handlers/wsgi.py +216 -0
- plain/internal/legacy/__init__.py +0 -0
- plain/internal/legacy/__main__.py +12 -0
- plain/internal/legacy/management/__init__.py +414 -0
- plain/internal/legacy/management/base.py +692 -0
- plain/internal/legacy/management/color.py +113 -0
- plain/internal/legacy/management/commands/__init__.py +0 -0
- plain/internal/legacy/management/commands/collectstatic.py +297 -0
- plain/internal/legacy/management/sql.py +67 -0
- plain/internal/legacy/management/utils.py +175 -0
- plain/json.py +40 -0
- plain/logs/README.md +24 -0
- plain/logs/__init__.py +5 -0
- plain/logs/configure.py +39 -0
- plain/logs/loggers.py +74 -0
- plain/logs/utils.py +46 -0
- plain/middleware/README.md +3 -0
- plain/middleware/__init__.py +0 -0
- plain/middleware/clickjacking.py +52 -0
- plain/middleware/common.py +87 -0
- plain/middleware/gzip.py +64 -0
- plain/middleware/security.py +64 -0
- plain/packages/README.md +41 -0
- plain/packages/__init__.py +4 -0
- plain/packages/config.py +259 -0
- plain/packages/registry.py +438 -0
- plain/paginator.py +187 -0
- plain/preflight/README.md +3 -0
- plain/preflight/__init__.py +38 -0
- plain/preflight/compatibility/__init__.py +0 -0
- plain/preflight/compatibility/django_4_0.py +20 -0
- plain/preflight/files.py +19 -0
- plain/preflight/messages.py +88 -0
- plain/preflight/registry.py +72 -0
- plain/preflight/security/__init__.py +0 -0
- plain/preflight/security/base.py +268 -0
- plain/preflight/security/csrf.py +40 -0
- plain/preflight/urls.py +117 -0
- plain/runtime/README.md +75 -0
- plain/runtime/__init__.py +61 -0
- plain/runtime/global_settings.py +199 -0
- plain/runtime/user_settings.py +353 -0
- plain/signals/README.md +14 -0
- plain/signals/__init__.py +5 -0
- plain/signals/dispatch/__init__.py +9 -0
- plain/signals/dispatch/dispatcher.py +320 -0
- plain/signals/dispatch/license.txt +35 -0
- plain/signing.py +299 -0
- plain/templates/README.md +20 -0
- plain/templates/__init__.py +6 -0
- plain/templates/core.py +24 -0
- plain/templates/jinja/README.md +227 -0
- plain/templates/jinja/__init__.py +22 -0
- plain/templates/jinja/defaults.py +119 -0
- plain/templates/jinja/extensions.py +39 -0
- plain/templates/jinja/filters.py +28 -0
- plain/templates/jinja/globals.py +19 -0
- plain/test/README.md +3 -0
- plain/test/__init__.py +16 -0
- plain/test/client.py +985 -0
- plain/test/utils.py +255 -0
- plain/urls/README.md +3 -0
- plain/urls/__init__.py +40 -0
- plain/urls/base.py +118 -0
- plain/urls/conf.py +94 -0
- plain/urls/converters.py +66 -0
- plain/urls/exceptions.py +9 -0
- plain/urls/resolvers.py +731 -0
- plain/utils/README.md +3 -0
- plain/utils/__init__.py +0 -0
- plain/utils/_os.py +52 -0
- plain/utils/cache.py +327 -0
- plain/utils/connection.py +84 -0
- plain/utils/crypto.py +76 -0
- plain/utils/datastructures.py +345 -0
- plain/utils/dateformat.py +329 -0
- plain/utils/dateparse.py +154 -0
- plain/utils/dates.py +76 -0
- plain/utils/deconstruct.py +54 -0
- plain/utils/decorators.py +90 -0
- plain/utils/deprecation.py +6 -0
- plain/utils/duration.py +44 -0
- plain/utils/email.py +12 -0
- plain/utils/encoding.py +235 -0
- plain/utils/functional.py +456 -0
- plain/utils/hashable.py +26 -0
- plain/utils/html.py +401 -0
- plain/utils/http.py +374 -0
- plain/utils/inspect.py +73 -0
- plain/utils/ipv6.py +46 -0
- plain/utils/itercompat.py +8 -0
- plain/utils/module_loading.py +69 -0
- plain/utils/regex_helper.py +353 -0
- plain/utils/safestring.py +72 -0
- plain/utils/termcolors.py +221 -0
- plain/utils/text.py +518 -0
- plain/utils/timesince.py +138 -0
- plain/utils/timezone.py +244 -0
- plain/utils/tree.py +126 -0
- plain/validators.py +603 -0
- plain/views/README.md +268 -0
- plain/views/__init__.py +18 -0
- plain/views/base.py +107 -0
- plain/views/csrf.py +24 -0
- plain/views/errors.py +25 -0
- plain/views/exceptions.py +4 -0
- plain/views/forms.py +76 -0
- plain/views/objects.py +229 -0
- plain/views/redirect.py +72 -0
- plain/views/templates.py +66 -0
- plain/wsgi.py +11 -0
- plain-0.1.0.dist-info/LICENSE +85 -0
- plain-0.1.0.dist-info/METADATA +51 -0
- plain-0.1.0.dist-info/RECORD +169 -0
- plain-0.1.0.dist-info/WHEEL +4 -0
- plain-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions for reversing a regular expression (used in reverse URL resolving).
|
|
3
|
+
Used internally by Plain and not intended for external use.
|
|
4
|
+
|
|
5
|
+
This is not, and is not intended to be, a complete reg-exp decompiler. It
|
|
6
|
+
should be good enough for a large class of URLS, however.
|
|
7
|
+
"""
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
from plain.utils.functional import SimpleLazyObject
|
|
11
|
+
|
|
12
|
+
# Mapping of an escape character to a representative of that class. So, e.g.,
|
|
13
|
+
# "\w" is replaced by "x" in a reverse URL. A value of None means to ignore
|
|
14
|
+
# this sequence. Any missing key is mapped to itself.
|
|
15
|
+
ESCAPE_MAPPINGS = {
|
|
16
|
+
"A": None,
|
|
17
|
+
"b": None,
|
|
18
|
+
"B": None,
|
|
19
|
+
"d": "0",
|
|
20
|
+
"D": "x",
|
|
21
|
+
"s": " ",
|
|
22
|
+
"S": "x",
|
|
23
|
+
"w": "x",
|
|
24
|
+
"W": "!",
|
|
25
|
+
"Z": None,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Choice(list):
|
|
30
|
+
"""Represent multiple possibilities at this point in a pattern string."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Group(list):
|
|
34
|
+
"""Represent a capturing group in the pattern string."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class NonCapture(list):
|
|
38
|
+
"""Represent a non-capturing group in the pattern string."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def normalize(pattern):
|
|
42
|
+
r"""
|
|
43
|
+
Given a reg-exp pattern, normalize it to an iterable of forms that
|
|
44
|
+
suffice for reverse matching. This does the following:
|
|
45
|
+
|
|
46
|
+
(1) For any repeating sections, keeps the minimum number of occurrences
|
|
47
|
+
permitted (this means zero for optional groups).
|
|
48
|
+
(2) If an optional group includes parameters, include one occurrence of
|
|
49
|
+
that group (along with the zero occurrence case from step (1)).
|
|
50
|
+
(3) Select the first (essentially an arbitrary) element from any character
|
|
51
|
+
class. Select an arbitrary character for any unordered class (e.g. '.'
|
|
52
|
+
or '\w') in the pattern.
|
|
53
|
+
(4) Ignore look-ahead and look-behind assertions.
|
|
54
|
+
(5) Raise an error on any disjunctive ('|') constructs.
|
|
55
|
+
|
|
56
|
+
Plain's URLs for forward resolving are either all positional arguments or
|
|
57
|
+
all keyword arguments. That is assumed here, as well. Although reverse
|
|
58
|
+
resolving can be done using positional args when keyword args are
|
|
59
|
+
specified, the two cannot be mixed in the same reverse() call.
|
|
60
|
+
"""
|
|
61
|
+
# Do a linear scan to work out the special features of this pattern. The
|
|
62
|
+
# idea is that we scan once here and collect all the information we need to
|
|
63
|
+
# make future decisions.
|
|
64
|
+
result = []
|
|
65
|
+
non_capturing_groups = []
|
|
66
|
+
consume_next = True
|
|
67
|
+
pattern_iter = next_char(iter(pattern))
|
|
68
|
+
num_args = 0
|
|
69
|
+
|
|
70
|
+
# A "while" loop is used here because later on we need to be able to peek
|
|
71
|
+
# at the next character and possibly go around without consuming another
|
|
72
|
+
# one at the top of the loop.
|
|
73
|
+
try:
|
|
74
|
+
ch, escaped = next(pattern_iter)
|
|
75
|
+
except StopIteration:
|
|
76
|
+
return [("", [])]
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
while True:
|
|
80
|
+
if escaped:
|
|
81
|
+
result.append(ch)
|
|
82
|
+
elif ch == ".":
|
|
83
|
+
# Replace "any character" with an arbitrary representative.
|
|
84
|
+
result.append(".")
|
|
85
|
+
elif ch == "|":
|
|
86
|
+
# FIXME: One day we'll should do this, but not in 1.0.
|
|
87
|
+
raise NotImplementedError("Awaiting Implementation")
|
|
88
|
+
elif ch == "^":
|
|
89
|
+
pass
|
|
90
|
+
elif ch == "$":
|
|
91
|
+
break
|
|
92
|
+
elif ch == ")":
|
|
93
|
+
# This can only be the end of a non-capturing group, since all
|
|
94
|
+
# other unescaped parentheses are handled by the grouping
|
|
95
|
+
# section later (and the full group is handled there).
|
|
96
|
+
#
|
|
97
|
+
# We regroup everything inside the capturing group so that it
|
|
98
|
+
# can be quantified, if necessary.
|
|
99
|
+
start = non_capturing_groups.pop()
|
|
100
|
+
inner = NonCapture(result[start:])
|
|
101
|
+
result = result[:start] + [inner]
|
|
102
|
+
elif ch == "[":
|
|
103
|
+
# Replace ranges with the first character in the range.
|
|
104
|
+
ch, escaped = next(pattern_iter)
|
|
105
|
+
result.append(ch)
|
|
106
|
+
ch, escaped = next(pattern_iter)
|
|
107
|
+
while escaped or ch != "]":
|
|
108
|
+
ch, escaped = next(pattern_iter)
|
|
109
|
+
elif ch == "(":
|
|
110
|
+
# Some kind of group.
|
|
111
|
+
ch, escaped = next(pattern_iter)
|
|
112
|
+
if ch != "?" or escaped:
|
|
113
|
+
# A positional group
|
|
114
|
+
name = "_%d" % num_args
|
|
115
|
+
num_args += 1
|
|
116
|
+
result.append(Group((("%%(%s)s" % name), name)))
|
|
117
|
+
walk_to_end(ch, pattern_iter)
|
|
118
|
+
else:
|
|
119
|
+
ch, escaped = next(pattern_iter)
|
|
120
|
+
if ch in "!=<":
|
|
121
|
+
# All of these are ignorable. Walk to the end of the
|
|
122
|
+
# group.
|
|
123
|
+
walk_to_end(ch, pattern_iter)
|
|
124
|
+
elif ch == ":":
|
|
125
|
+
# Non-capturing group
|
|
126
|
+
non_capturing_groups.append(len(result))
|
|
127
|
+
elif ch != "P":
|
|
128
|
+
# Anything else, other than a named group, is something
|
|
129
|
+
# we cannot reverse.
|
|
130
|
+
raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch)
|
|
131
|
+
else:
|
|
132
|
+
ch, escaped = next(pattern_iter)
|
|
133
|
+
if ch not in ("<", "="):
|
|
134
|
+
raise ValueError(
|
|
135
|
+
"Non-reversible reg-exp portion: '(?P%s'" % ch
|
|
136
|
+
)
|
|
137
|
+
# We are in a named capturing group. Extra the name and
|
|
138
|
+
# then skip to the end.
|
|
139
|
+
if ch == "<":
|
|
140
|
+
terminal_char = ">"
|
|
141
|
+
# We are in a named backreference.
|
|
142
|
+
else:
|
|
143
|
+
terminal_char = ")"
|
|
144
|
+
name = []
|
|
145
|
+
ch, escaped = next(pattern_iter)
|
|
146
|
+
while ch != terminal_char:
|
|
147
|
+
name.append(ch)
|
|
148
|
+
ch, escaped = next(pattern_iter)
|
|
149
|
+
param = "".join(name)
|
|
150
|
+
# Named backreferences have already consumed the
|
|
151
|
+
# parenthesis.
|
|
152
|
+
if terminal_char != ")":
|
|
153
|
+
result.append(Group((("%%(%s)s" % param), param)))
|
|
154
|
+
walk_to_end(ch, pattern_iter)
|
|
155
|
+
else:
|
|
156
|
+
result.append(Group((("%%(%s)s" % param), None)))
|
|
157
|
+
elif ch in "*?+{":
|
|
158
|
+
# Quantifiers affect the previous item in the result list.
|
|
159
|
+
count, ch = get_quantifier(ch, pattern_iter)
|
|
160
|
+
if ch:
|
|
161
|
+
# We had to look ahead, but it wasn't need to compute the
|
|
162
|
+
# quantifier, so use this character next time around the
|
|
163
|
+
# main loop.
|
|
164
|
+
consume_next = False
|
|
165
|
+
|
|
166
|
+
if count == 0:
|
|
167
|
+
if contains(result[-1], Group):
|
|
168
|
+
# If we are quantifying a capturing group (or
|
|
169
|
+
# something containing such a group) and the minimum is
|
|
170
|
+
# zero, we must also handle the case of one occurrence
|
|
171
|
+
# being present. All the quantifiers (except {0,0},
|
|
172
|
+
# which we conveniently ignore) that have a 0 minimum
|
|
173
|
+
# also allow a single occurrence.
|
|
174
|
+
result[-1] = Choice([None, result[-1]])
|
|
175
|
+
else:
|
|
176
|
+
result.pop()
|
|
177
|
+
elif count > 1:
|
|
178
|
+
result.extend([result[-1]] * (count - 1))
|
|
179
|
+
else:
|
|
180
|
+
# Anything else is a literal.
|
|
181
|
+
result.append(ch)
|
|
182
|
+
|
|
183
|
+
if consume_next:
|
|
184
|
+
ch, escaped = next(pattern_iter)
|
|
185
|
+
consume_next = True
|
|
186
|
+
except StopIteration:
|
|
187
|
+
pass
|
|
188
|
+
except NotImplementedError:
|
|
189
|
+
# A case of using the disjunctive form. No results for you!
|
|
190
|
+
return [("", [])]
|
|
191
|
+
|
|
192
|
+
return list(zip(*flatten_result(result)))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def next_char(input_iter):
|
|
196
|
+
r"""
|
|
197
|
+
An iterator that yields the next character from "pattern_iter", respecting
|
|
198
|
+
escape sequences. An escaped character is replaced by a representative of
|
|
199
|
+
its class (e.g. \w -> "x"). If the escaped character is one that is
|
|
200
|
+
skipped, it is not returned (the next character is returned instead).
|
|
201
|
+
|
|
202
|
+
Yield the next character, along with a boolean indicating whether it is a
|
|
203
|
+
raw (unescaped) character or not.
|
|
204
|
+
"""
|
|
205
|
+
for ch in input_iter:
|
|
206
|
+
if ch != "\\":
|
|
207
|
+
yield ch, False
|
|
208
|
+
continue
|
|
209
|
+
ch = next(input_iter)
|
|
210
|
+
representative = ESCAPE_MAPPINGS.get(ch, ch)
|
|
211
|
+
if representative is None:
|
|
212
|
+
continue
|
|
213
|
+
yield representative, True
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def walk_to_end(ch, input_iter):
|
|
217
|
+
"""
|
|
218
|
+
The iterator is currently inside a capturing group. Walk to the close of
|
|
219
|
+
this group, skipping over any nested groups and handling escaped
|
|
220
|
+
parentheses correctly.
|
|
221
|
+
"""
|
|
222
|
+
if ch == "(":
|
|
223
|
+
nesting = 1
|
|
224
|
+
else:
|
|
225
|
+
nesting = 0
|
|
226
|
+
for ch, escaped in input_iter:
|
|
227
|
+
if escaped:
|
|
228
|
+
continue
|
|
229
|
+
elif ch == "(":
|
|
230
|
+
nesting += 1
|
|
231
|
+
elif ch == ")":
|
|
232
|
+
if not nesting:
|
|
233
|
+
return
|
|
234
|
+
nesting -= 1
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def get_quantifier(ch, input_iter):
|
|
238
|
+
"""
|
|
239
|
+
Parse a quantifier from the input, where "ch" is the first character in the
|
|
240
|
+
quantifier.
|
|
241
|
+
|
|
242
|
+
Return the minimum number of occurrences permitted by the quantifier and
|
|
243
|
+
either None or the next character from the input_iter if the next character
|
|
244
|
+
is not part of the quantifier.
|
|
245
|
+
"""
|
|
246
|
+
if ch in "*?+":
|
|
247
|
+
try:
|
|
248
|
+
ch2, escaped = next(input_iter)
|
|
249
|
+
except StopIteration:
|
|
250
|
+
ch2 = None
|
|
251
|
+
if ch2 == "?":
|
|
252
|
+
ch2 = None
|
|
253
|
+
if ch == "+":
|
|
254
|
+
return 1, ch2
|
|
255
|
+
return 0, ch2
|
|
256
|
+
|
|
257
|
+
quant = []
|
|
258
|
+
while ch != "}":
|
|
259
|
+
ch, escaped = next(input_iter)
|
|
260
|
+
quant.append(ch)
|
|
261
|
+
quant = quant[:-1]
|
|
262
|
+
values = "".join(quant).split(",")
|
|
263
|
+
|
|
264
|
+
# Consume the trailing '?', if necessary.
|
|
265
|
+
try:
|
|
266
|
+
ch, escaped = next(input_iter)
|
|
267
|
+
except StopIteration:
|
|
268
|
+
ch = None
|
|
269
|
+
if ch == "?":
|
|
270
|
+
ch = None
|
|
271
|
+
return int(values[0]), ch
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def contains(source, inst):
|
|
275
|
+
"""
|
|
276
|
+
Return True if the "source" contains an instance of "inst". False,
|
|
277
|
+
otherwise.
|
|
278
|
+
"""
|
|
279
|
+
if isinstance(source, inst):
|
|
280
|
+
return True
|
|
281
|
+
if isinstance(source, NonCapture):
|
|
282
|
+
for elt in source:
|
|
283
|
+
if contains(elt, inst):
|
|
284
|
+
return True
|
|
285
|
+
return False
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def flatten_result(source):
|
|
289
|
+
"""
|
|
290
|
+
Turn the given source sequence into a list of reg-exp possibilities and
|
|
291
|
+
their arguments. Return a list of strings and a list of argument lists.
|
|
292
|
+
Each of the two lists will be of the same length.
|
|
293
|
+
"""
|
|
294
|
+
if source is None:
|
|
295
|
+
return [""], [[]]
|
|
296
|
+
if isinstance(source, Group):
|
|
297
|
+
if source[1] is None:
|
|
298
|
+
params = []
|
|
299
|
+
else:
|
|
300
|
+
params = [source[1]]
|
|
301
|
+
return [source[0]], [params]
|
|
302
|
+
result = [""]
|
|
303
|
+
result_args = [[]]
|
|
304
|
+
pos = last = 0
|
|
305
|
+
for pos, elt in enumerate(source):
|
|
306
|
+
if isinstance(elt, str):
|
|
307
|
+
continue
|
|
308
|
+
piece = "".join(source[last:pos])
|
|
309
|
+
if isinstance(elt, Group):
|
|
310
|
+
piece += elt[0]
|
|
311
|
+
param = elt[1]
|
|
312
|
+
else:
|
|
313
|
+
param = None
|
|
314
|
+
last = pos + 1
|
|
315
|
+
for i in range(len(result)):
|
|
316
|
+
result[i] += piece
|
|
317
|
+
if param:
|
|
318
|
+
result_args[i].append(param)
|
|
319
|
+
if isinstance(elt, Choice | NonCapture):
|
|
320
|
+
if isinstance(elt, NonCapture):
|
|
321
|
+
elt = [elt]
|
|
322
|
+
inner_result, inner_args = [], []
|
|
323
|
+
for item in elt:
|
|
324
|
+
res, args = flatten_result(item)
|
|
325
|
+
inner_result.extend(res)
|
|
326
|
+
inner_args.extend(args)
|
|
327
|
+
new_result = []
|
|
328
|
+
new_args = []
|
|
329
|
+
for item, args in zip(result, result_args):
|
|
330
|
+
for i_item, i_args in zip(inner_result, inner_args):
|
|
331
|
+
new_result.append(item + i_item)
|
|
332
|
+
new_args.append(args[:] + i_args)
|
|
333
|
+
result = new_result
|
|
334
|
+
result_args = new_args
|
|
335
|
+
if pos >= last:
|
|
336
|
+
piece = "".join(source[last:])
|
|
337
|
+
for i in range(len(result)):
|
|
338
|
+
result[i] += piece
|
|
339
|
+
return result, result_args
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _lazy_re_compile(regex, flags=0):
|
|
343
|
+
"""Lazily compile a regex with flags."""
|
|
344
|
+
|
|
345
|
+
def _compile():
|
|
346
|
+
# Compile the regex if it was not passed pre-compiled.
|
|
347
|
+
if isinstance(regex, str | bytes):
|
|
348
|
+
return re.compile(regex, flags)
|
|
349
|
+
else:
|
|
350
|
+
assert not flags, "flags must be empty if regex is passed pre-compiled"
|
|
351
|
+
return regex
|
|
352
|
+
|
|
353
|
+
return SimpleLazyObject(_compile)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions for working with "safe strings": strings that can be displayed safely
|
|
3
|
+
without further escaping in HTML. Marking something as a "safe string" means
|
|
4
|
+
that the producer of the string has already turned characters that should not
|
|
5
|
+
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from functools import wraps
|
|
9
|
+
|
|
10
|
+
from plain.utils.functional import keep_lazy
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SafeData:
|
|
14
|
+
__slots__ = ()
|
|
15
|
+
|
|
16
|
+
def __html__(self):
|
|
17
|
+
"""
|
|
18
|
+
Return the html representation of a string for interoperability.
|
|
19
|
+
|
|
20
|
+
This allows other template engines to understand Plain's SafeData.
|
|
21
|
+
"""
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SafeString(str, SafeData):
|
|
26
|
+
"""
|
|
27
|
+
A str subclass that has been specifically marked as "safe" for HTML output
|
|
28
|
+
purposes.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
__slots__ = ()
|
|
32
|
+
|
|
33
|
+
def __add__(self, rhs):
|
|
34
|
+
"""
|
|
35
|
+
Concatenating a safe string with another safe bytestring or
|
|
36
|
+
safe string is safe. Otherwise, the result is no longer safe.
|
|
37
|
+
"""
|
|
38
|
+
t = super().__add__(rhs)
|
|
39
|
+
if isinstance(rhs, SafeData):
|
|
40
|
+
return SafeString(t)
|
|
41
|
+
return t
|
|
42
|
+
|
|
43
|
+
def __str__(self):
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
SafeText = SafeString # For backwards compatibility since Plain 2.0.
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _safety_decorator(safety_marker, func):
|
|
51
|
+
@wraps(func)
|
|
52
|
+
def wrapper(*args, **kwargs):
|
|
53
|
+
return safety_marker(func(*args, **kwargs))
|
|
54
|
+
|
|
55
|
+
return wrapper
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@keep_lazy(SafeString)
|
|
59
|
+
def mark_safe(s):
|
|
60
|
+
"""
|
|
61
|
+
Explicitly mark a string as safe for (HTML) output purposes. The returned
|
|
62
|
+
object can be used everywhere a string is appropriate.
|
|
63
|
+
|
|
64
|
+
If used on a method as a decorator, mark the returned data as safe.
|
|
65
|
+
|
|
66
|
+
Can be called multiple times on a single string.
|
|
67
|
+
"""
|
|
68
|
+
if hasattr(s, "__html__"):
|
|
69
|
+
return s
|
|
70
|
+
if callable(s):
|
|
71
|
+
return _safety_decorator(mark_safe, s)
|
|
72
|
+
return SafeString(s)
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""
|
|
2
|
+
termcolors.py
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
color_names = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white")
|
|
6
|
+
foreground = {color_names[x]: "3%s" % x for x in range(8)}
|
|
7
|
+
background = {color_names[x]: "4%s" % x for x in range(8)}
|
|
8
|
+
|
|
9
|
+
RESET = "0"
|
|
10
|
+
opt_dict = {
|
|
11
|
+
"bold": "1",
|
|
12
|
+
"underscore": "4",
|
|
13
|
+
"blink": "5",
|
|
14
|
+
"reverse": "7",
|
|
15
|
+
"conceal": "8",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def colorize(text="", opts=(), **kwargs):
|
|
20
|
+
"""
|
|
21
|
+
Return your text, enclosed in ANSI graphics codes.
|
|
22
|
+
|
|
23
|
+
Depends on the keyword arguments 'fg' and 'bg', and the contents of
|
|
24
|
+
the opts tuple/list.
|
|
25
|
+
|
|
26
|
+
Return the RESET code if no parameters are given.
|
|
27
|
+
|
|
28
|
+
Valid colors:
|
|
29
|
+
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
|
|
30
|
+
|
|
31
|
+
Valid options:
|
|
32
|
+
'bold'
|
|
33
|
+
'underscore'
|
|
34
|
+
'blink'
|
|
35
|
+
'reverse'
|
|
36
|
+
'conceal'
|
|
37
|
+
'noreset' - string will not be auto-terminated with the RESET code
|
|
38
|
+
|
|
39
|
+
Examples:
|
|
40
|
+
colorize('hello', fg='red', bg='blue', opts=('blink',))
|
|
41
|
+
colorize()
|
|
42
|
+
colorize('goodbye', opts=('underscore',))
|
|
43
|
+
print(colorize('first line', fg='red', opts=('noreset',)))
|
|
44
|
+
print('this should be red too')
|
|
45
|
+
print(colorize('and so should this'))
|
|
46
|
+
print('this should not be red')
|
|
47
|
+
"""
|
|
48
|
+
code_list = []
|
|
49
|
+
if text == "" and len(opts) == 1 and opts[0] == "reset":
|
|
50
|
+
return "\x1b[%sm" % RESET
|
|
51
|
+
for k, v in kwargs.items():
|
|
52
|
+
if k == "fg":
|
|
53
|
+
code_list.append(foreground[v])
|
|
54
|
+
elif k == "bg":
|
|
55
|
+
code_list.append(background[v])
|
|
56
|
+
for o in opts:
|
|
57
|
+
if o in opt_dict:
|
|
58
|
+
code_list.append(opt_dict[o])
|
|
59
|
+
if "noreset" not in opts:
|
|
60
|
+
text = "{}\x1b[{}m".format(text or "", RESET)
|
|
61
|
+
return "{}{}".format(("\x1b[%sm" % ";".join(code_list)), text or "")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def make_style(opts=(), **kwargs):
|
|
65
|
+
"""
|
|
66
|
+
Return a function with default parameters for colorize()
|
|
67
|
+
|
|
68
|
+
Example:
|
|
69
|
+
bold_red = make_style(opts=('bold',), fg='red')
|
|
70
|
+
print(bold_red('hello'))
|
|
71
|
+
KEYWORD = make_style(fg='yellow')
|
|
72
|
+
COMMENT = make_style(fg='blue', opts=('bold',))
|
|
73
|
+
"""
|
|
74
|
+
return lambda text: colorize(text, opts, **kwargs)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
NOCOLOR_PALETTE = "nocolor"
|
|
78
|
+
DARK_PALETTE = "dark"
|
|
79
|
+
LIGHT_PALETTE = "light"
|
|
80
|
+
|
|
81
|
+
PALETTES = {
|
|
82
|
+
NOCOLOR_PALETTE: {
|
|
83
|
+
"ERROR": {},
|
|
84
|
+
"SUCCESS": {},
|
|
85
|
+
"WARNING": {},
|
|
86
|
+
"NOTICE": {},
|
|
87
|
+
"SQL_FIELD": {},
|
|
88
|
+
"SQL_COLTYPE": {},
|
|
89
|
+
"SQL_KEYWORD": {},
|
|
90
|
+
"SQL_TABLE": {},
|
|
91
|
+
"HTTP_INFO": {},
|
|
92
|
+
"HTTP_SUCCESS": {},
|
|
93
|
+
"HTTP_REDIRECT": {},
|
|
94
|
+
"HTTP_NOT_MODIFIED": {},
|
|
95
|
+
"HTTP_BAD_REQUEST": {},
|
|
96
|
+
"HTTP_NOT_FOUND": {},
|
|
97
|
+
"HTTP_SERVER_ERROR": {},
|
|
98
|
+
"MIGRATE_HEADING": {},
|
|
99
|
+
"MIGRATE_LABEL": {},
|
|
100
|
+
},
|
|
101
|
+
DARK_PALETTE: {
|
|
102
|
+
"ERROR": {"fg": "red", "opts": ("bold",)},
|
|
103
|
+
"SUCCESS": {"fg": "green", "opts": ("bold",)},
|
|
104
|
+
"WARNING": {"fg": "yellow", "opts": ("bold",)},
|
|
105
|
+
"NOTICE": {"fg": "red"},
|
|
106
|
+
"SQL_FIELD": {"fg": "green", "opts": ("bold",)},
|
|
107
|
+
"SQL_COLTYPE": {"fg": "green"},
|
|
108
|
+
"SQL_KEYWORD": {"fg": "yellow"},
|
|
109
|
+
"SQL_TABLE": {"opts": ("bold",)},
|
|
110
|
+
"HTTP_INFO": {"opts": ("bold",)},
|
|
111
|
+
"HTTP_SUCCESS": {},
|
|
112
|
+
"HTTP_REDIRECT": {"fg": "green"},
|
|
113
|
+
"HTTP_NOT_MODIFIED": {"fg": "cyan"},
|
|
114
|
+
"HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)},
|
|
115
|
+
"HTTP_NOT_FOUND": {"fg": "yellow"},
|
|
116
|
+
"HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)},
|
|
117
|
+
"MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)},
|
|
118
|
+
"MIGRATE_LABEL": {"opts": ("bold",)},
|
|
119
|
+
},
|
|
120
|
+
LIGHT_PALETTE: {
|
|
121
|
+
"ERROR": {"fg": "red", "opts": ("bold",)},
|
|
122
|
+
"SUCCESS": {"fg": "green", "opts": ("bold",)},
|
|
123
|
+
"WARNING": {"fg": "yellow", "opts": ("bold",)},
|
|
124
|
+
"NOTICE": {"fg": "red"},
|
|
125
|
+
"SQL_FIELD": {"fg": "green", "opts": ("bold",)},
|
|
126
|
+
"SQL_COLTYPE": {"fg": "green"},
|
|
127
|
+
"SQL_KEYWORD": {"fg": "blue"},
|
|
128
|
+
"SQL_TABLE": {"opts": ("bold",)},
|
|
129
|
+
"HTTP_INFO": {"opts": ("bold",)},
|
|
130
|
+
"HTTP_SUCCESS": {},
|
|
131
|
+
"HTTP_REDIRECT": {"fg": "green", "opts": ("bold",)},
|
|
132
|
+
"HTTP_NOT_MODIFIED": {"fg": "green"},
|
|
133
|
+
"HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)},
|
|
134
|
+
"HTTP_NOT_FOUND": {"fg": "red"},
|
|
135
|
+
"HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)},
|
|
136
|
+
"MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)},
|
|
137
|
+
"MIGRATE_LABEL": {"opts": ("bold",)},
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
DEFAULT_PALETTE = DARK_PALETTE
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse_color_setting(config_string):
|
|
144
|
+
"""Parse a DJANGO_COLORS environment variable to produce the system palette
|
|
145
|
+
|
|
146
|
+
The general form of a palette definition is:
|
|
147
|
+
|
|
148
|
+
"palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
|
|
149
|
+
|
|
150
|
+
where:
|
|
151
|
+
palette is a named palette; one of 'light', 'dark', or 'nocolor'.
|
|
152
|
+
role is a named style used by Django
|
|
153
|
+
fg is a foreground color.
|
|
154
|
+
bg is a background color.
|
|
155
|
+
option is a display options.
|
|
156
|
+
|
|
157
|
+
Specifying a named palette is the same as manually specifying the individual
|
|
158
|
+
definitions for each role. Any individual definitions following the palette
|
|
159
|
+
definition will augment the base palette definition.
|
|
160
|
+
|
|
161
|
+
Valid roles:
|
|
162
|
+
'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype',
|
|
163
|
+
'sql_keyword', 'sql_table', 'http_info', 'http_success',
|
|
164
|
+
'http_redirect', 'http_not_modified', 'http_bad_request',
|
|
165
|
+
'http_not_found', 'http_server_error', 'migrate_heading',
|
|
166
|
+
'migrate_label'
|
|
167
|
+
|
|
168
|
+
Valid colors:
|
|
169
|
+
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
|
|
170
|
+
|
|
171
|
+
Valid options:
|
|
172
|
+
'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset'
|
|
173
|
+
"""
|
|
174
|
+
if not config_string:
|
|
175
|
+
return PALETTES[DEFAULT_PALETTE]
|
|
176
|
+
|
|
177
|
+
# Split the color configuration into parts
|
|
178
|
+
parts = config_string.lower().split(";")
|
|
179
|
+
palette = PALETTES[NOCOLOR_PALETTE].copy()
|
|
180
|
+
for part in parts:
|
|
181
|
+
if part in PALETTES:
|
|
182
|
+
# A default palette has been specified
|
|
183
|
+
palette.update(PALETTES[part])
|
|
184
|
+
elif "=" in part:
|
|
185
|
+
# Process a palette defining string
|
|
186
|
+
definition = {}
|
|
187
|
+
|
|
188
|
+
# Break the definition into the role,
|
|
189
|
+
# plus the list of specific instructions.
|
|
190
|
+
# The role must be in upper case
|
|
191
|
+
role, instructions = part.split("=")
|
|
192
|
+
role = role.upper()
|
|
193
|
+
|
|
194
|
+
styles = instructions.split(",")
|
|
195
|
+
styles.reverse()
|
|
196
|
+
|
|
197
|
+
# The first instruction can contain a slash
|
|
198
|
+
# to break apart fg/bg.
|
|
199
|
+
colors = styles.pop().split("/")
|
|
200
|
+
colors.reverse()
|
|
201
|
+
fg = colors.pop()
|
|
202
|
+
if fg in color_names:
|
|
203
|
+
definition["fg"] = fg
|
|
204
|
+
if colors and colors[-1] in color_names:
|
|
205
|
+
definition["bg"] = colors[-1]
|
|
206
|
+
|
|
207
|
+
# All remaining instructions are options
|
|
208
|
+
opts = tuple(s for s in styles if s in opt_dict)
|
|
209
|
+
if opts:
|
|
210
|
+
definition["opts"] = opts
|
|
211
|
+
|
|
212
|
+
# The nocolor palette has all available roles.
|
|
213
|
+
# Use that palette as the basis for determining
|
|
214
|
+
# if the role is valid.
|
|
215
|
+
if role in PALETTES[NOCOLOR_PALETTE] and definition:
|
|
216
|
+
palette[role] = definition
|
|
217
|
+
|
|
218
|
+
# If there are no colors specified, return the empty palette.
|
|
219
|
+
if palette == PALETTES[NOCOLOR_PALETTE]:
|
|
220
|
+
return None
|
|
221
|
+
return palette
|