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/text.py ADDED
@@ -0,0 +1,518 @@
1
+ import gzip
2
+ import re
3
+ import secrets
4
+ import unicodedata
5
+ from gzip import GzipFile
6
+ from gzip import compress as gzip_compress
7
+ from io import BytesIO
8
+
9
+ from plain.exceptions import SuspiciousFileOperation
10
+ from plain.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
11
+ from plain.utils.regex_helper import _lazy_re_compile
12
+
13
+
14
+ @keep_lazy_text
15
+ def capfirst(x):
16
+ """Capitalize the first letter of a string."""
17
+ if not x:
18
+ return x
19
+ if not isinstance(x, str):
20
+ x = str(x)
21
+ return x[0].upper() + x[1:]
22
+
23
+
24
+ # Set up regular expressions
25
+ re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S)
26
+ re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S)
27
+ re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S)
28
+ re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
29
+ re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
30
+
31
+
32
+ @keep_lazy_text
33
+ def wrap(text, width):
34
+ """
35
+ A word-wrap function that preserves existing line breaks. Expects that
36
+ existing line breaks are posix newlines.
37
+
38
+ Preserve all white space except added line breaks consume the space on
39
+ which they break the line.
40
+
41
+ Don't wrap long words, thus the output text may have lines longer than
42
+ ``width``.
43
+ """
44
+
45
+ def _generator():
46
+ for line in text.splitlines(True): # True keeps trailing linebreaks
47
+ max_width = min((line.endswith("\n") and width + 1 or width), width)
48
+ while len(line) > max_width:
49
+ space = line[: max_width + 1].rfind(" ") + 1
50
+ if space == 0:
51
+ space = line.find(" ") + 1
52
+ if space == 0:
53
+ yield line
54
+ line = ""
55
+ break
56
+ yield "%s\n" % line[: space - 1]
57
+ line = line[space:]
58
+ max_width = min((line.endswith("\n") and width + 1 or width), width)
59
+ if line:
60
+ yield line
61
+
62
+ return "".join(_generator())
63
+
64
+
65
+ class Truncator(SimpleLazyObject):
66
+ """
67
+ An object used to truncate text, either by characters or words.
68
+ """
69
+
70
+ def __init__(self, text):
71
+ super().__init__(lambda: str(text))
72
+
73
+ def add_truncation_text(self, text, truncate=None):
74
+ if truncate is None:
75
+ truncate = "%(truncated_text)s…"
76
+ if "%(truncated_text)s" in truncate:
77
+ return truncate % {"truncated_text": text}
78
+ # The truncation text didn't contain the %(truncated_text)s string
79
+ # replacement argument so just append it to the text.
80
+ if text.endswith(truncate):
81
+ # But don't append the truncation text if the current text already
82
+ # ends in this.
83
+ return text
84
+ return f"{text}{truncate}"
85
+
86
+ def chars(self, num, truncate=None, html=False):
87
+ """
88
+ Return the text truncated to be no longer than the specified number
89
+ of characters.
90
+
91
+ `truncate` specifies what should be used to notify that the string has
92
+ been truncated, defaulting to a translatable string of an ellipsis.
93
+ """
94
+ self._setup()
95
+ length = int(num)
96
+ text = unicodedata.normalize("NFC", self._wrapped)
97
+
98
+ # Calculate the length to truncate to (max length - end_text length)
99
+ truncate_len = length
100
+ for char in self.add_truncation_text("", truncate):
101
+ if not unicodedata.combining(char):
102
+ truncate_len -= 1
103
+ if truncate_len == 0:
104
+ break
105
+ if html:
106
+ return self._truncate_html(length, truncate, text, truncate_len, False)
107
+ return self._text_chars(length, truncate, text, truncate_len)
108
+
109
+ def _text_chars(self, length, truncate, text, truncate_len):
110
+ """Truncate a string after a certain number of chars."""
111
+ s_len = 0
112
+ end_index = None
113
+ for i, char in enumerate(text):
114
+ if unicodedata.combining(char):
115
+ # Don't consider combining characters
116
+ # as adding to the string length
117
+ continue
118
+ s_len += 1
119
+ if end_index is None and s_len > truncate_len:
120
+ end_index = i
121
+ if s_len > length:
122
+ # Return the truncated string
123
+ return self.add_truncation_text(text[: end_index or 0], truncate)
124
+
125
+ # Return the original string since no truncation was necessary
126
+ return text
127
+
128
+ def words(self, num, truncate=None, html=False):
129
+ """
130
+ Truncate a string after a certain number of words. `truncate` specifies
131
+ what should be used to notify that the string has been truncated,
132
+ defaulting to ellipsis.
133
+ """
134
+ self._setup()
135
+ length = int(num)
136
+ if html:
137
+ return self._truncate_html(length, truncate, self._wrapped, length, True)
138
+ return self._text_words(length, truncate)
139
+
140
+ def _text_words(self, length, truncate):
141
+ """
142
+ Truncate a string after a certain number of words.
143
+
144
+ Strip newlines in the string.
145
+ """
146
+ words = self._wrapped.split()
147
+ if len(words) > length:
148
+ words = words[:length]
149
+ return self.add_truncation_text(" ".join(words), truncate)
150
+ return " ".join(words)
151
+
152
+ def _truncate_html(self, length, truncate, text, truncate_len, words):
153
+ """
154
+ Truncate HTML to a certain number of chars (not counting tags and
155
+ comments), or, if words is True, then to a certain number of words.
156
+ Close opened tags if they were correctly closed in the given HTML.
157
+
158
+ Preserve newlines in the HTML.
159
+ """
160
+ if words and length <= 0:
161
+ return ""
162
+
163
+ html4_singlets = (
164
+ "br",
165
+ "col",
166
+ "link",
167
+ "base",
168
+ "img",
169
+ "param",
170
+ "area",
171
+ "hr",
172
+ "input",
173
+ )
174
+
175
+ # Count non-HTML chars/words and keep note of open tags
176
+ pos = 0
177
+ end_text_pos = 0
178
+ current_len = 0
179
+ open_tags = []
180
+
181
+ regex = re_words if words else re_chars
182
+
183
+ while current_len <= length:
184
+ m = regex.search(text, pos)
185
+ if not m:
186
+ # Checked through whole string
187
+ break
188
+ pos = m.end(0)
189
+ if m[1]:
190
+ # It's an actual non-HTML word or char
191
+ current_len += 1
192
+ if current_len == truncate_len:
193
+ end_text_pos = pos
194
+ continue
195
+ # Check for tag
196
+ tag = re_tag.match(m[0])
197
+ if not tag or current_len >= truncate_len:
198
+ # Don't worry about non tags or tags after our truncate point
199
+ continue
200
+ closing_tag, tagname, self_closing = tag.groups()
201
+ # Element names are always case-insensitive
202
+ tagname = tagname.lower()
203
+ if self_closing or tagname in html4_singlets:
204
+ pass
205
+ elif closing_tag:
206
+ # Check for match in open tags list
207
+ try:
208
+ i = open_tags.index(tagname)
209
+ except ValueError:
210
+ pass
211
+ else:
212
+ # SGML: An end tag closes, back to the matching start tag,
213
+ # all unclosed intervening start tags with omitted end tags
214
+ open_tags = open_tags[i + 1 :]
215
+ else:
216
+ # Add it to the start of the open tags list
217
+ open_tags.insert(0, tagname)
218
+
219
+ if current_len <= length:
220
+ return text
221
+ out = text[:end_text_pos]
222
+ truncate_text = self.add_truncation_text("", truncate)
223
+ if truncate_text:
224
+ out += truncate_text
225
+ # Close any tags still open
226
+ for tag in open_tags:
227
+ out += "</%s>" % tag
228
+ # Return string
229
+ return out
230
+
231
+
232
+ @keep_lazy_text
233
+ def get_valid_filename(name):
234
+ """
235
+ Return the given string converted to a string that can be used for a clean
236
+ filename. Remove leading and trailing spaces; convert other spaces to
237
+ underscores; and remove anything that is not an alphanumeric, dash,
238
+ underscore, or dot.
239
+ >>> get_valid_filename("john's portrait in 2004.jpg")
240
+ 'johns_portrait_in_2004.jpg'
241
+ """
242
+ s = str(name).strip().replace(" ", "_")
243
+ s = re.sub(r"(?u)[^-\w.]", "", s)
244
+ if s in {"", ".", ".."}:
245
+ raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
246
+ return s
247
+
248
+
249
+ @keep_lazy_text
250
+ def get_text_list(list_, last_word="or"):
251
+ """
252
+ >>> get_text_list(['a', 'b', 'c', 'd'])
253
+ 'a, b, c or d'
254
+ >>> get_text_list(['a', 'b', 'c'], 'and')
255
+ 'a, b and c'
256
+ >>> get_text_list(['a', 'b'], 'and')
257
+ 'a and b'
258
+ >>> get_text_list(['a'])
259
+ 'a'
260
+ >>> get_text_list([])
261
+ ''
262
+ """
263
+ if not list_:
264
+ return ""
265
+ if len(list_) == 1:
266
+ return str(list_[0])
267
+ return "{} {} {}".format(
268
+ # Translators: This string is used as a separator between list elements
269
+ ", ".join(str(i) for i in list_[:-1]),
270
+ str(last_word),
271
+ str(list_[-1]),
272
+ )
273
+
274
+
275
+ @keep_lazy_text
276
+ def normalize_newlines(text):
277
+ """Normalize CRLF and CR newlines to just LF."""
278
+ return re_newlines.sub("\n", str(text))
279
+
280
+
281
+ @keep_lazy_text
282
+ def phone2numeric(phone):
283
+ """Convert a phone number with letters into its numeric equivalent."""
284
+ char2number = {
285
+ "a": "2",
286
+ "b": "2",
287
+ "c": "2",
288
+ "d": "3",
289
+ "e": "3",
290
+ "f": "3",
291
+ "g": "4",
292
+ "h": "4",
293
+ "i": "4",
294
+ "j": "5",
295
+ "k": "5",
296
+ "l": "5",
297
+ "m": "6",
298
+ "n": "6",
299
+ "o": "6",
300
+ "p": "7",
301
+ "q": "7",
302
+ "r": "7",
303
+ "s": "7",
304
+ "t": "8",
305
+ "u": "8",
306
+ "v": "8",
307
+ "w": "9",
308
+ "x": "9",
309
+ "y": "9",
310
+ "z": "9",
311
+ }
312
+ return "".join(char2number.get(c, c) for c in phone.lower())
313
+
314
+
315
+ def _get_random_filename(max_random_bytes):
316
+ return b"a" * secrets.randbelow(max_random_bytes)
317
+
318
+
319
+ def compress_string(s, *, max_random_bytes=None):
320
+ compressed_data = gzip_compress(s, compresslevel=6, mtime=0)
321
+
322
+ if not max_random_bytes:
323
+ return compressed_data
324
+
325
+ compressed_view = memoryview(compressed_data)
326
+ header = bytearray(compressed_view[:10])
327
+ header[3] = gzip.FNAME
328
+
329
+ filename = _get_random_filename(max_random_bytes) + b"\x00"
330
+
331
+ return bytes(header) + filename + compressed_view[10:]
332
+
333
+
334
+ class StreamingBuffer(BytesIO):
335
+ def read(self):
336
+ ret = self.getvalue()
337
+ self.seek(0)
338
+ self.truncate()
339
+ return ret
340
+
341
+
342
+ # Like compress_string, but for iterators of strings.
343
+ def compress_sequence(sequence, *, max_random_bytes=None):
344
+ buf = StreamingBuffer()
345
+ filename = _get_random_filename(max_random_bytes) if max_random_bytes else None
346
+ with GzipFile(
347
+ filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0
348
+ ) as zfile:
349
+ # Output headers...
350
+ yield buf.read()
351
+ for item in sequence:
352
+ zfile.write(item)
353
+ data = buf.read()
354
+ if data:
355
+ yield data
356
+ yield buf.read()
357
+
358
+
359
+ # Expression to match some_token and some_token="with spaces" (and similarly
360
+ # for single-quoted strings).
361
+ smart_split_re = _lazy_re_compile(
362
+ r"""
363
+ ((?:
364
+ [^\s'"]*
365
+ (?:
366
+ (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
367
+ [^\s'"]*
368
+ )+
369
+ ) | \S+)
370
+ """,
371
+ re.VERBOSE,
372
+ )
373
+
374
+
375
+ def smart_split(text):
376
+ r"""
377
+ Generator that splits a string by spaces, leaving quoted phrases together.
378
+ Supports both single and double quotes, and supports escaping quotes with
379
+ backslashes. In the output, strings will keep their initial and trailing
380
+ quote marks and escaped quotes will remain escaped (the results can then
381
+ be further processed with unescape_string_literal()).
382
+
383
+ >>> list(smart_split(r'This is "a person\'s" test.'))
384
+ ['This', 'is', '"a person\\\'s"', 'test.']
385
+ >>> list(smart_split(r"Another 'person\'s' test."))
386
+ ['Another', "'person\\'s'", 'test.']
387
+ >>> list(smart_split(r'A "\"funky\" style" test.'))
388
+ ['A', '"\\"funky\\" style"', 'test.']
389
+ """
390
+ for bit in smart_split_re.finditer(str(text)):
391
+ yield bit[0]
392
+
393
+
394
+ @keep_lazy_text
395
+ def unescape_string_literal(s):
396
+ r"""
397
+ Convert quoted string literals to unquoted strings with escaped quotes and
398
+ backslashes unquoted::
399
+
400
+ >>> unescape_string_literal('"abc"')
401
+ 'abc'
402
+ >>> unescape_string_literal("'abc'")
403
+ 'abc'
404
+ >>> unescape_string_literal('"a \"bc\""')
405
+ 'a "bc"'
406
+ >>> unescape_string_literal("'\'ab\' c'")
407
+ "'ab' c"
408
+ """
409
+ if not s or s[0] not in "\"'" or s[-1] != s[0]:
410
+ raise ValueError("Not a string literal: %r" % s)
411
+ quote = s[0]
412
+ return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
413
+
414
+
415
+ @keep_lazy_text
416
+ def slugify(value, allow_unicode=False):
417
+ """
418
+ Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
419
+ dashes to single dashes. Remove characters that aren't alphanumerics,
420
+ underscores, or hyphens. Convert to lowercase. Also strip leading and
421
+ trailing whitespace, dashes, and underscores.
422
+ """
423
+ value = str(value)
424
+ if allow_unicode:
425
+ value = unicodedata.normalize("NFKC", value)
426
+ else:
427
+ value = (
428
+ unicodedata.normalize("NFKD", value)
429
+ .encode("ascii", "ignore")
430
+ .decode("ascii")
431
+ )
432
+ value = re.sub(r"[^\w\s-]", "", value.lower())
433
+ return re.sub(r"[-\s]+", "-", value).strip("-_")
434
+
435
+
436
+ def camel_case_to_spaces(value):
437
+ """
438
+ Split CamelCase and convert to lowercase. Strip surrounding whitespace.
439
+ """
440
+ return re_camel_case.sub(r" \1", value).strip().lower()
441
+
442
+
443
+ def _format_lazy(format_string, *args, **kwargs):
444
+ """
445
+ Apply str.format() on 'format_string' where format_string, args,
446
+ and/or kwargs might be lazy.
447
+ """
448
+ return format_string.format(*args, **kwargs)
449
+
450
+
451
+ def pluralize(singular, plural, number):
452
+ if number == 1:
453
+ return singular
454
+ else:
455
+ return plural
456
+
457
+
458
+ def pluralize_lazy(singular, plural, number):
459
+ def _lazy_number_unpickle(func, resultclass, number, kwargs):
460
+ return lazy_number(func, resultclass, number=number, **kwargs)
461
+
462
+ def lazy_number(func, resultclass, number=None, **kwargs):
463
+ if isinstance(number, int):
464
+ kwargs["number"] = number
465
+ proxy = lazy(func, resultclass)(**kwargs)
466
+ else:
467
+ original_kwargs = kwargs.copy()
468
+
469
+ class NumberAwareString(resultclass):
470
+ def __bool__(self):
471
+ return bool(kwargs["singular"])
472
+
473
+ def _get_number_value(self, values):
474
+ try:
475
+ return values[number]
476
+ except KeyError:
477
+ raise KeyError(
478
+ "Your dictionary lacks key '%s'. Please provide "
479
+ "it, because it is required to determine whether "
480
+ "string is singular or plural." % number
481
+ )
482
+
483
+ def _translate(self, number_value):
484
+ kwargs["number"] = number_value
485
+ return func(**kwargs)
486
+
487
+ def format(self, *args, **kwargs):
488
+ number_value = (
489
+ self._get_number_value(kwargs) if kwargs and number else args[0]
490
+ )
491
+ return self._translate(number_value).format(*args, **kwargs)
492
+
493
+ def __mod__(self, rhs):
494
+ if isinstance(rhs, dict) and number:
495
+ number_value = self._get_number_value(rhs)
496
+ else:
497
+ number_value = rhs
498
+ translated = self._translate(number_value)
499
+ try:
500
+ translated %= rhs
501
+ except TypeError:
502
+ # String doesn't contain a placeholder for the number.
503
+ pass
504
+ return translated
505
+
506
+ proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(
507
+ **kwargs
508
+ )
509
+ proxy.__reduce__ = lambda: (
510
+ _lazy_number_unpickle,
511
+ (func, resultclass, number, original_kwargs),
512
+ )
513
+ return proxy
514
+
515
+ return lazy_number(pluralize, str, singular=singular, plural=plural, number=number)
516
+
517
+
518
+ format_lazy = lazy(_format_lazy, str)
@@ -0,0 +1,138 @@
1
+ import datetime
2
+
3
+ from plain.utils.html import avoid_wrapping
4
+ from plain.utils.text import pluralize_lazy
5
+ from plain.utils.timezone import is_aware
6
+
7
+ TIME_STRINGS = {
8
+ "year": pluralize_lazy("%(num)d year", "%(num)d years", "num"),
9
+ "month": pluralize_lazy("%(num)d month", "%(num)d months", "num"),
10
+ "week": pluralize_lazy("%(num)d week", "%(num)d weeks", "num"),
11
+ "day": pluralize_lazy("%(num)d day", "%(num)d days", "num"),
12
+ "hour": pluralize_lazy("%(num)d hour", "%(num)d hours", "num"),
13
+ "minute": pluralize_lazy("%(num)d minute", "%(num)d minutes", "num"),
14
+ }
15
+
16
+ TIME_STRINGS_KEYS = list(TIME_STRINGS.keys())
17
+
18
+ TIME_CHUNKS = [
19
+ 60 * 60 * 24 * 7, # week
20
+ 60 * 60 * 24, # day
21
+ 60 * 60, # hour
22
+ 60, # minute
23
+ ]
24
+
25
+ MONTHS_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
26
+
27
+
28
+ def timesince(d, now=None, reversed=False, time_strings=None, depth=2):
29
+ """
30
+ Take two datetime objects and return the time between d and now as a nicely
31
+ formatted string, e.g. "10 minutes". If d occurs after now, return
32
+ "0 minutes".
33
+
34
+ Units used are years, months, weeks, days, hours, and minutes.
35
+ Seconds and microseconds are ignored.
36
+
37
+ The algorithm takes into account the varying duration of years and months.
38
+ There is exactly "1 year, 1 month" between 2013/02/10 and 2014/03/10,
39
+ but also between 2007/08/10 and 2008/09/10 despite the delta being 393 days
40
+ in the former case and 397 in the latter.
41
+
42
+ Up to `depth` adjacent units will be displayed. For example,
43
+ "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but
44
+ "2 weeks, 3 hours" and "1 year, 5 days" are not.
45
+
46
+ `time_strings` is an optional dict of strings to replace the default
47
+ TIME_STRINGS dict.
48
+
49
+ `depth` is an optional integer to control the number of adjacent time
50
+ units returned.
51
+
52
+ Originally adapted from
53
+ https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
54
+ Modified to improve results for years and months.
55
+ """
56
+ if time_strings is None:
57
+ time_strings = TIME_STRINGS
58
+ if depth <= 0:
59
+ raise ValueError("depth must be greater than 0.")
60
+ # Convert datetime.date to datetime.datetime for comparison.
61
+ if not isinstance(d, datetime.datetime):
62
+ d = datetime.datetime(d.year, d.month, d.day)
63
+ if now and not isinstance(now, datetime.datetime):
64
+ now = datetime.datetime(now.year, now.month, now.day)
65
+
66
+ now = now or datetime.datetime.now(datetime.timezone.utc if is_aware(d) else None)
67
+
68
+ if reversed:
69
+ d, now = now, d
70
+ delta = now - d
71
+
72
+ # Ignore microseconds.
73
+ since = delta.days * 24 * 60 * 60 + delta.seconds
74
+ if since <= 0:
75
+ # d is in the future compared to now, stop processing.
76
+ return avoid_wrapping(time_strings["minute"] % {"num": 0})
77
+
78
+ # Get years and months.
79
+ total_months = (now.year - d.year) * 12 + (now.month - d.month)
80
+ if d.day > now.day or (d.day == now.day and d.time() > now.time()):
81
+ total_months -= 1
82
+ years, months = divmod(total_months, 12)
83
+
84
+ # Calculate the remaining time.
85
+ # Create a "pivot" datetime shifted from d by years and months, then use
86
+ # that to determine the other parts.
87
+ if years or months:
88
+ pivot_year = d.year + years
89
+ pivot_month = d.month + months
90
+ if pivot_month > 12:
91
+ pivot_month -= 12
92
+ pivot_year += 1
93
+ pivot = datetime.datetime(
94
+ pivot_year,
95
+ pivot_month,
96
+ min(MONTHS_DAYS[pivot_month - 1], d.day),
97
+ d.hour,
98
+ d.minute,
99
+ d.second,
100
+ tzinfo=d.tzinfo,
101
+ )
102
+ else:
103
+ pivot = d
104
+ remaining_time = (now - pivot).total_seconds()
105
+ partials = [years, months]
106
+ for chunk in TIME_CHUNKS:
107
+ count = int(remaining_time // chunk)
108
+ partials.append(count)
109
+ remaining_time -= chunk * count
110
+
111
+ # Find the first non-zero part (if any) and then build the result, until
112
+ # depth.
113
+ i = 0
114
+ for i, value in enumerate(partials):
115
+ if value != 0:
116
+ break
117
+ else:
118
+ return avoid_wrapping(time_strings["minute"] % {"num": 0})
119
+
120
+ result = []
121
+ current_depth = 0
122
+ while i < len(TIME_STRINGS_KEYS) and current_depth < depth:
123
+ value = partials[i]
124
+ if value == 0:
125
+ break
126
+ name = TIME_STRINGS_KEYS[i]
127
+ result.append(avoid_wrapping(time_strings[name] % {"num": value}))
128
+ current_depth += 1
129
+ i += 1
130
+
131
+ return ", ".join(result)
132
+
133
+
134
+ def timeuntil(d, now=None, time_strings=None, depth=2):
135
+ """
136
+ Like timesince, but return a string measuring the time until the given time.
137
+ """
138
+ return timesince(d, now, reversed=True, time_strings=time_strings, depth=depth)