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
@@ -0,0 +1,345 @@
1
+ import copy
2
+ from collections.abc import Mapping
3
+
4
+
5
+ class OrderedSet:
6
+ """
7
+ A set which keeps the ordering of the inserted items.
8
+ """
9
+
10
+ def __init__(self, iterable=None):
11
+ self.dict = dict.fromkeys(iterable or ())
12
+
13
+ def add(self, item):
14
+ self.dict[item] = None
15
+
16
+ def remove(self, item):
17
+ del self.dict[item]
18
+
19
+ def discard(self, item):
20
+ try:
21
+ self.remove(item)
22
+ except KeyError:
23
+ pass
24
+
25
+ def __iter__(self):
26
+ return iter(self.dict)
27
+
28
+ def __reversed__(self):
29
+ return reversed(self.dict)
30
+
31
+ def __contains__(self, item):
32
+ return item in self.dict
33
+
34
+ def __bool__(self):
35
+ return bool(self.dict)
36
+
37
+ def __len__(self):
38
+ return len(self.dict)
39
+
40
+ def __repr__(self):
41
+ data = repr(list(self.dict)) if self.dict else ""
42
+ return f"{self.__class__.__qualname__}({data})"
43
+
44
+
45
+ class MultiValueDictKeyError(KeyError):
46
+ pass
47
+
48
+
49
+ class MultiValueDict(dict):
50
+ """
51
+ A subclass of dictionary customized to handle multiple values for the
52
+ same key.
53
+
54
+ >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
55
+ >>> d['name']
56
+ 'Simon'
57
+ >>> d.getlist('name')
58
+ ['Adrian', 'Simon']
59
+ >>> d.getlist('doesnotexist')
60
+ []
61
+ >>> d.getlist('doesnotexist', ['Adrian', 'Simon'])
62
+ ['Adrian', 'Simon']
63
+ >>> d.get('lastname', 'nonexistent')
64
+ 'nonexistent'
65
+ >>> d.setlist('lastname', ['Holovaty', 'Willison'])
66
+
67
+ This class exists to solve the irritating problem raised by cgi.parse_qs,
68
+ which returns a list for every key, even though most web forms submit
69
+ single name-value pairs.
70
+ """
71
+
72
+ def __init__(self, key_to_list_mapping=()):
73
+ super().__init__(key_to_list_mapping)
74
+
75
+ def __repr__(self):
76
+ return f"<{self.__class__.__name__}: {super().__repr__()}>"
77
+
78
+ def __getitem__(self, key):
79
+ """
80
+ Return the last data value for this key, or [] if it's an empty list;
81
+ raise KeyError if not found.
82
+ """
83
+ try:
84
+ list_ = super().__getitem__(key)
85
+ except KeyError:
86
+ raise MultiValueDictKeyError(key)
87
+ try:
88
+ return list_[-1]
89
+ except IndexError:
90
+ return []
91
+
92
+ def __setitem__(self, key, value):
93
+ super().__setitem__(key, [value])
94
+
95
+ def __copy__(self):
96
+ return self.__class__([(k, v[:]) for k, v in self.lists()])
97
+
98
+ def __deepcopy__(self, memo):
99
+ result = self.__class__()
100
+ memo[id(self)] = result
101
+ for key, value in dict.items(self):
102
+ dict.__setitem__(
103
+ result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)
104
+ )
105
+ return result
106
+
107
+ def __getstate__(self):
108
+ return {**self.__dict__, "_data": {k: self._getlist(k) for k in self}}
109
+
110
+ def __setstate__(self, obj_dict):
111
+ data = obj_dict.pop("_data", {})
112
+ for k, v in data.items():
113
+ self.setlist(k, v)
114
+ self.__dict__.update(obj_dict)
115
+
116
+ def get(self, key, default=None):
117
+ """
118
+ Return the last data value for the passed key. If key doesn't exist
119
+ or value is an empty list, return `default`.
120
+ """
121
+ try:
122
+ val = self[key]
123
+ except KeyError:
124
+ return default
125
+ if val == []:
126
+ return default
127
+ return val
128
+
129
+ def _getlist(self, key, default=None, force_list=False):
130
+ """
131
+ Return a list of values for the key.
132
+
133
+ Used internally to manipulate values list. If force_list is True,
134
+ return a new copy of values.
135
+ """
136
+ try:
137
+ values = super().__getitem__(key)
138
+ except KeyError:
139
+ if default is None:
140
+ return []
141
+ return default
142
+ else:
143
+ if force_list:
144
+ values = list(values) if values is not None else None
145
+ return values
146
+
147
+ def getlist(self, key, default=None):
148
+ """
149
+ Return the list of values for the key. If key doesn't exist, return a
150
+ default value.
151
+ """
152
+ return self._getlist(key, default, force_list=True)
153
+
154
+ def setlist(self, key, list_):
155
+ super().__setitem__(key, list_)
156
+
157
+ def setdefault(self, key, default=None):
158
+ if key not in self:
159
+ self[key] = default
160
+ # Do not return default here because __setitem__() may store
161
+ # another value -- QueryDict.__setitem__() does. Look it up.
162
+ return self[key]
163
+
164
+ def setlistdefault(self, key, default_list=None):
165
+ if key not in self:
166
+ if default_list is None:
167
+ default_list = []
168
+ self.setlist(key, default_list)
169
+ # Do not return default_list here because setlist() may store
170
+ # another value -- QueryDict.setlist() does. Look it up.
171
+ return self._getlist(key)
172
+
173
+ def appendlist(self, key, value):
174
+ """Append an item to the internal list associated with key."""
175
+ self.setlistdefault(key).append(value)
176
+
177
+ def items(self):
178
+ """
179
+ Yield (key, value) pairs, where value is the last item in the list
180
+ associated with the key.
181
+ """
182
+ for key in self:
183
+ yield key, self[key]
184
+
185
+ def lists(self):
186
+ """Yield (key, list) pairs."""
187
+ return iter(super().items())
188
+
189
+ def values(self):
190
+ """Yield the last value on every key list."""
191
+ for key in self:
192
+ yield self[key]
193
+
194
+ def copy(self):
195
+ """Return a shallow copy of this object."""
196
+ return copy.copy(self)
197
+
198
+ def update(self, *args, **kwargs):
199
+ """Extend rather than replace existing key lists."""
200
+ if len(args) > 1:
201
+ raise TypeError("update expected at most 1 argument, got %d" % len(args))
202
+ if args:
203
+ arg = args[0]
204
+ if isinstance(arg, MultiValueDict):
205
+ for key, value_list in arg.lists():
206
+ self.setlistdefault(key).extend(value_list)
207
+ else:
208
+ if isinstance(arg, Mapping):
209
+ arg = arg.items()
210
+ for key, value in arg:
211
+ self.setlistdefault(key).append(value)
212
+ for key, value in kwargs.items():
213
+ self.setlistdefault(key).append(value)
214
+
215
+ def dict(self):
216
+ """Return current object as a dict with singular values."""
217
+ return {key: self[key] for key in self}
218
+
219
+
220
+ class ImmutableList(tuple):
221
+ """
222
+ A tuple-like object that raises useful errors when it is asked to mutate.
223
+
224
+ Example::
225
+
226
+ >>> a = ImmutableList(range(5), warning="You cannot mutate this.")
227
+ >>> a[3] = '4'
228
+ Traceback (most recent call last):
229
+ ...
230
+ AttributeError: You cannot mutate this.
231
+ """
232
+
233
+ def __new__(cls, *args, warning="ImmutableList object is immutable.", **kwargs):
234
+ self = tuple.__new__(cls, *args, **kwargs)
235
+ self.warning = warning
236
+ return self
237
+
238
+ def complain(self, *args, **kwargs):
239
+ raise AttributeError(self.warning)
240
+
241
+ # All list mutation functions complain.
242
+ __delitem__ = complain
243
+ __delslice__ = complain
244
+ __iadd__ = complain
245
+ __imul__ = complain
246
+ __setitem__ = complain
247
+ __setslice__ = complain
248
+ append = complain
249
+ extend = complain
250
+ insert = complain
251
+ pop = complain
252
+ remove = complain
253
+ sort = complain
254
+ reverse = complain
255
+
256
+
257
+ class DictWrapper(dict):
258
+ """
259
+ Wrap accesses to a dictionary so that certain values (those starting with
260
+ the specified prefix) are passed through a function before being returned.
261
+ The prefix is removed before looking up the real value.
262
+
263
+ Used by the SQL construction code to ensure that values are correctly
264
+ quoted before being used.
265
+ """
266
+
267
+ def __init__(self, data, func, prefix):
268
+ super().__init__(data)
269
+ self.func = func
270
+ self.prefix = prefix
271
+
272
+ def __getitem__(self, key):
273
+ """
274
+ Retrieve the real value after stripping the prefix string (if
275
+ present). If the prefix is present, pass the value through self.func
276
+ before returning, otherwise return the raw value.
277
+ """
278
+ use_func = key.startswith(self.prefix)
279
+ key = key.removeprefix(self.prefix)
280
+ value = super().__getitem__(key)
281
+ if use_func:
282
+ return self.func(value)
283
+ return value
284
+
285
+
286
+ class CaseInsensitiveMapping(Mapping):
287
+ """
288
+ Mapping allowing case-insensitive key lookups. Original case of keys is
289
+ preserved for iteration and string representation.
290
+
291
+ Example::
292
+
293
+ >>> ci_map = CaseInsensitiveMapping({'name': 'Jane'})
294
+ >>> ci_map['Name']
295
+ Jane
296
+ >>> ci_map['NAME']
297
+ Jane
298
+ >>> ci_map['name']
299
+ Jane
300
+ >>> ci_map # original case preserved
301
+ {'name': 'Jane'}
302
+ """
303
+
304
+ def __init__(self, data):
305
+ self._store = {k.lower(): (k, v) for k, v in self._unpack_items(data)}
306
+
307
+ def __getitem__(self, key):
308
+ return self._store[key.lower()][1]
309
+
310
+ def __len__(self):
311
+ return len(self._store)
312
+
313
+ def __eq__(self, other):
314
+ return isinstance(other, Mapping) and {
315
+ k.lower(): v for k, v in self.items()
316
+ } == {k.lower(): v for k, v in other.items()}
317
+
318
+ def __iter__(self):
319
+ return (original_key for original_key, value in self._store.values())
320
+
321
+ def __repr__(self):
322
+ return repr(dict(self._store.values()))
323
+
324
+ def copy(self):
325
+ return self
326
+
327
+ @staticmethod
328
+ def _unpack_items(data):
329
+ # Explicitly test for dict first as the common case for performance,
330
+ # avoiding abc's __instancecheck__ and _abc_instancecheck for the
331
+ # general Mapping case.
332
+ if isinstance(data, dict | Mapping):
333
+ yield from data.items()
334
+ return
335
+ for i, elem in enumerate(data):
336
+ if len(elem) != 2:
337
+ raise ValueError(
338
+ f"dictionary update sequence element #{i} has length {len(elem)}; "
339
+ "2 is required."
340
+ )
341
+ if not isinstance(elem[0], str):
342
+ raise ValueError(
343
+ "Element key %r invalid, only strings are allowed" % elem[0]
344
+ )
345
+ yield elem
@@ -0,0 +1,329 @@
1
+ """
2
+ PHP date() style date formatting
3
+ See https://www.php.net/date for format strings
4
+
5
+ Usage:
6
+ >>> from datetime import datetime
7
+ >>> d = datetime.now()
8
+ >>> df = DateFormat(d)
9
+ >>> print(df.format('jS F Y H:i'))
10
+ 7th October 2003 11:39
11
+ >>>
12
+ """
13
+ import calendar
14
+ from datetime import date, datetime, time
15
+ from email.utils import format_datetime as format_datetime_rfc5322
16
+
17
+ from plain.utils.dates import (
18
+ MONTHS,
19
+ MONTHS_3,
20
+ MONTHS_ALT,
21
+ MONTHS_AP,
22
+ WEEKDAYS,
23
+ WEEKDAYS_ABBR,
24
+ )
25
+ from plain.utils.regex_helper import _lazy_re_compile
26
+ from plain.utils.timezone import (
27
+ _datetime_ambiguous_or_imaginary,
28
+ get_default_timezone,
29
+ is_naive,
30
+ make_aware,
31
+ )
32
+
33
+ re_formatchars = _lazy_re_compile(r"(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])")
34
+ re_escaped = _lazy_re_compile(r"\\(.)")
35
+
36
+
37
+ class Formatter:
38
+ def format(self, formatstr):
39
+ pieces = []
40
+ for i, piece in enumerate(re_formatchars.split(str(formatstr))):
41
+ if i % 2:
42
+ if type(self.data) is date and hasattr(TimeFormat, piece):
43
+ raise TypeError(
44
+ "The format for date objects may not contain "
45
+ "time-related format specifiers (found '%s')." % piece
46
+ )
47
+ pieces.append(str(getattr(self, piece)()))
48
+ elif piece:
49
+ pieces.append(re_escaped.sub(r"\1", piece))
50
+ return "".join(pieces)
51
+
52
+
53
+ class TimeFormat(Formatter):
54
+ def __init__(self, obj):
55
+ self.data = obj
56
+ self.timezone = None
57
+
58
+ if isinstance(obj, datetime):
59
+ # Timezone is only supported when formatting datetime objects, not
60
+ # date objects (timezone information not appropriate), or time
61
+ # objects (against established Plain policy).
62
+ if is_naive(obj):
63
+ timezone = get_default_timezone()
64
+ else:
65
+ timezone = obj.tzinfo
66
+ if not _datetime_ambiguous_or_imaginary(obj, timezone):
67
+ self.timezone = timezone
68
+
69
+ def a(self):
70
+ "'a.m.' or 'p.m.'"
71
+ if self.data.hour > 11:
72
+ return "p.m."
73
+ return "a.m."
74
+
75
+ def A(self):
76
+ "'AM' or 'PM'"
77
+ if self.data.hour > 11:
78
+ return "PM"
79
+ return "AM"
80
+
81
+ def e(self):
82
+ """
83
+ Timezone name.
84
+
85
+ If timezone information is not available, return an empty string.
86
+ """
87
+ if not self.timezone:
88
+ return ""
89
+
90
+ try:
91
+ if getattr(self.data, "tzinfo", None):
92
+ return self.data.tzname() or ""
93
+ except NotImplementedError:
94
+ pass
95
+ return ""
96
+
97
+ def f(self):
98
+ """
99
+ Time, in 12-hour hours and minutes, with minutes left off if they're
100
+ zero.
101
+ Examples: '1', '1:30', '2:05', '2'
102
+ Proprietary extension.
103
+ """
104
+ hour = self.data.hour % 12 or 12
105
+ minute = self.data.minute
106
+ return "%d:%02d" % (hour, minute) if minute else hour
107
+
108
+ def g(self):
109
+ "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
110
+ return self.data.hour % 12 or 12
111
+
112
+ def G(self):
113
+ "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
114
+ return self.data.hour
115
+
116
+ def h(self):
117
+ "Hour, 12-hour format; i.e. '01' to '12'"
118
+ return "%02d" % (self.data.hour % 12 or 12)
119
+
120
+ def H(self):
121
+ "Hour, 24-hour format; i.e. '00' to '23'"
122
+ return "%02d" % self.data.hour
123
+
124
+ def i(self):
125
+ "Minutes; i.e. '00' to '59'"
126
+ return "%02d" % self.data.minute
127
+
128
+ def O(self): # NOQA: E743, E741
129
+ """
130
+ Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
131
+
132
+ If timezone information is not available, return an empty string.
133
+ """
134
+ if self.timezone is None:
135
+ return ""
136
+
137
+ offset = self.timezone.utcoffset(self.data)
138
+ seconds = offset.days * 86400 + offset.seconds
139
+ sign = "-" if seconds < 0 else "+"
140
+ seconds = abs(seconds)
141
+ return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
142
+
143
+ def P(self):
144
+ """
145
+ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
146
+ if they're zero and the strings 'midnight' and 'noon' if appropriate.
147
+ Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
148
+ Proprietary extension.
149
+ """
150
+ if self.data.minute == 0 and self.data.hour == 0:
151
+ return "midnight"
152
+ if self.data.minute == 0 and self.data.hour == 12:
153
+ return "noon"
154
+ return f"{self.f()} {self.a()}"
155
+
156
+ def s(self):
157
+ "Seconds; i.e. '00' to '59'"
158
+ return "%02d" % self.data.second
159
+
160
+ def T(self):
161
+ """
162
+ Time zone of this machine; e.g. 'EST' or 'MDT'.
163
+
164
+ If timezone information is not available, return an empty string.
165
+ """
166
+ if self.timezone is None:
167
+ return ""
168
+
169
+ return str(self.timezone.tzname(self.data))
170
+
171
+ def u(self):
172
+ "Microseconds; i.e. '000000' to '999999'"
173
+ return "%06d" % self.data.microsecond
174
+
175
+ def Z(self):
176
+ """
177
+ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
178
+ timezones west of UTC is always negative, and for those east of UTC is
179
+ always positive.
180
+
181
+ If timezone information is not available, return an empty string.
182
+ """
183
+ if self.timezone is None:
184
+ return ""
185
+
186
+ offset = self.timezone.utcoffset(self.data)
187
+
188
+ # `offset` is a datetime.timedelta. For negative values (to the west of
189
+ # UTC) only days can be negative (days=-1) and seconds are always
190
+ # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
191
+ # Positive offsets have days=0
192
+ return offset.days * 86400 + offset.seconds
193
+
194
+
195
+ class DateFormat(TimeFormat):
196
+ def b(self):
197
+ "Month, textual, 3 letters, lowercase; e.g. 'jan'"
198
+ return MONTHS_3[self.data.month]
199
+
200
+ def c(self):
201
+ """
202
+ ISO 8601 Format
203
+ Example : '2008-01-02T10:30:00.000123'
204
+ """
205
+ return self.data.isoformat()
206
+
207
+ def d(self):
208
+ "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
209
+ return "%02d" % self.data.day
210
+
211
+ def D(self):
212
+ "Day of the week, textual, 3 letters; e.g. 'Fri'"
213
+ return WEEKDAYS_ABBR[self.data.weekday()]
214
+
215
+ def E(self):
216
+ "Alternative month names as required by some locales. Proprietary extension."
217
+ return MONTHS_ALT[self.data.month]
218
+
219
+ def F(self):
220
+ "Month, textual, long; e.g. 'January'"
221
+ return MONTHS[self.data.month]
222
+
223
+ def I(self): # NOQA: E743, E741
224
+ "'1' if daylight saving time, '0' otherwise."
225
+ if self.timezone is None:
226
+ return ""
227
+ return "1" if self.timezone.dst(self.data) else "0"
228
+
229
+ def j(self):
230
+ "Day of the month without leading zeros; i.e. '1' to '31'"
231
+ return self.data.day
232
+
233
+ def l(self): # NOQA: E743, E741
234
+ "Day of the week, textual, long; e.g. 'Friday'"
235
+ return WEEKDAYS[self.data.weekday()]
236
+
237
+ def L(self):
238
+ "Boolean for whether it is a leap year; i.e. True or False"
239
+ return calendar.isleap(self.data.year)
240
+
241
+ def m(self):
242
+ "Month; i.e. '01' to '12'"
243
+ return "%02d" % self.data.month
244
+
245
+ def M(self):
246
+ "Month, textual, 3 letters; e.g. 'Jan'"
247
+ return MONTHS_3[self.data.month].title()
248
+
249
+ def n(self):
250
+ "Month without leading zeros; i.e. '1' to '12'"
251
+ return self.data.month
252
+
253
+ def N(self):
254
+ "Month abbreviation in Associated Press style. Proprietary extension."
255
+ return MONTHS_AP[self.data.month]
256
+
257
+ def o(self):
258
+ "ISO 8601 year number matching the ISO week number (W)"
259
+ return self.data.isocalendar().year
260
+
261
+ def r(self):
262
+ "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
263
+ value = self.data
264
+ if not isinstance(value, datetime):
265
+ # Assume midnight in default timezone if datetime.date provided.
266
+ default_timezone = get_default_timezone()
267
+ value = datetime.combine(value, time.min).replace(tzinfo=default_timezone)
268
+ elif is_naive(value):
269
+ value = make_aware(value, timezone=self.timezone)
270
+ return format_datetime_rfc5322(value)
271
+
272
+ def S(self):
273
+ """
274
+ English ordinal suffix for the day of the month, 2 characters; i.e.
275
+ 'st', 'nd', 'rd' or 'th'.
276
+ """
277
+ if self.data.day in (11, 12, 13): # Special case
278
+ return "th"
279
+ last = self.data.day % 10
280
+ if last == 1:
281
+ return "st"
282
+ if last == 2:
283
+ return "nd"
284
+ if last == 3:
285
+ return "rd"
286
+ return "th"
287
+
288
+ def t(self):
289
+ "Number of days in the given month; i.e. '28' to '31'"
290
+ return calendar.monthrange(self.data.year, self.data.month)[1]
291
+
292
+ def U(self):
293
+ "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
294
+ value = self.data
295
+ if not isinstance(value, datetime):
296
+ value = datetime.combine(value, time.min)
297
+ return int(value.timestamp())
298
+
299
+ def w(self):
300
+ "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
301
+ return (self.data.weekday() + 1) % 7
302
+
303
+ def W(self):
304
+ "ISO-8601 week number of year, weeks starting on Monday"
305
+ return self.data.isocalendar().week
306
+
307
+ def y(self):
308
+ """Year, 2 digits with leading zeros; e.g. '99'."""
309
+ return "%02d" % (self.data.year % 100)
310
+
311
+ def Y(self):
312
+ """Year, 4 digits with leading zeros; e.g. '1999'."""
313
+ return "%04d" % self.data.year
314
+
315
+ def z(self):
316
+ """Day of the year, i.e. 1 to 366."""
317
+ return self.data.timetuple().tm_yday
318
+
319
+
320
+ def format(value, format_string):
321
+ "Convenience function"
322
+ df = DateFormat(value)
323
+ return df.format(format_string)
324
+
325
+
326
+ def time_format(value, format_string):
327
+ "Convenience function"
328
+ tf = TimeFormat(value)
329
+ return tf.format(format_string)