-
Notifications
You must be signed in to change notification settings - Fork 0
/
enviable.py
2181 lines (1993 loc) · 82.4 KB
/
enviable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
a small module for wrapping over environment variables (pulled from os.environ)
which provides convenience methods to fetch and check various data types
(including iterables) in what I'd charitably hope is a sensible way.
Explicitly doesn't attempt to read from any .env or .envrc file, because that
doesn't describe valid examples or which things may/should be set into the
environment. It becomes an absolute pot-luck.
Tracks requested environment variables and their default/fallback/example values, and
whether or not the fallback was used. Never tracks the actual environment value.
If this package isn't to your liking, there's **plenty** of others, and I'm
largely suffering from Not-Invented-Here syndrome.
All methods exposed by the Environment accept a key and a default.
The key is the environment variable to search for.
The default MUST be a string, as it is subject to the same parsing as if it had
been found in the environment, and thus serves as a documented example of a valid
value to export as an environment variable. Enforced value documentation!
A short series of examples follow; see the README.rst file for a fuller explanation::
from enviable import env
DEBUG = env.bool("DEBUG", "off")
GIT_HASH = env.hex("COMMIT_REF", "11ff3fe8ccfa4bbd9c144f68b84c80f6")
SERVER_EMAIL = env.email("DEFAULT_EMAIL", "a@b.com")
VALID_OPTION = env.one_of("VAR_NAME", "3", choices="1,2,3,4")
DYANMIC_IMPORT = env.importable("MY_MODULE", "path.to.mymodule")
LOCAL_FILE = env.filepath("ACCESS_KEYS", "/valid/path/to/keys.json")
API_URL = env.web_address("API_URL", "https://example.com/")
NUMBERS = env.tuple("NUMBERS", "(12,3,456)", converter=env.ensure.int)
UNORDERED_NUMBERS = env.frozenset("NUMBERS", "12, 3, 456", converter=env.ensure.int)
Failing to successfully convert (or just validate) the value immediately halts execution by raising
`EnvironmentCastError` which is a subclass of `ValueError` - it is recommended
that you only catch the former.
Should be able to handle the following:
- text
- integer
- boolean
- uuid (with and without hyphens)
- email (checks the string is email-like. Does not fully parse/validate, because that's a fool's errand)
- hex (validates the string)
- base64 encoded data (validates it decodes)
- decimal
- importable python paths (validates the string)
- file paths (validates the file exists and is readable)
- directories (validates the directory exists)
- URLs (sanity-checks the string ... ish)
- tuples/lists/sets/frozensets of any of the above
- dictionaries
- json
If Django is installed (sorry, I'm lazy) it should also handle:
- datetime
- date
- time
Running this file directly (`python enviable.py`) should execute a small test suite
which ought to pass. Please open an ticket if it doesn't.
"""
from __future__ import absolute_import, unicode_literals
import base64
import binascii
import decimal
import functools
import itertools
import json
import logging
import operator
import os
import re
import string
import sys
import tokenize
import uuid
import datetime as dt
from io import TextIOBase
from urllib.parse import urlparse, parse_qsl, unquote
try:
from typing import (
Text,
Union,
Set,
Optional,
Callable,
Iterable,
Any,
Tuple,
List,
FrozenSet,
Mapping,
Iterator,
Dict,
)
except ImportError:
pass
try:
from six import string_types
except ImportError:
string_types = (str,)
try:
from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.timezone import utc
CAN_PARSE_TEMPORAL = True
HAS_DJANGO = CAN_PARSE_TEMPORAL_DJANGO = True
except ImportError:
HAS_DJANGO = CAN_PARSE_TEMPORAL_DJANGO = False
# Python 3.7+ can at least parse a subset of ISO 8601 strings, like:
# YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
# YYYY-MM-DD
# HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]
try:
dt.datetime.fromisoformat
dt.date.fromisoformat
dt.time.fromisoformat
except AttributeError:
def temporal_failure(v): # type: ignore
raise NotImplementedError(
"I've not implemented parsing of dates/datetimes/times without depending on Django or Python 3.7+, sorry chum"
)
parse_date = temporal_failure
parse_datetime = temporal_failure
parse_time = temporal_failure
utc = None
CAN_PARSE_TEMPORAL = False
else:
def temporal_parser(v, handler):
try:
return handler(v)
except ValueError:
# Return None so that the rest of the date/datetime/time casting
# can try and run. Emulate's Django's parser which returns None
# for invalid inputs ... for reasons.
return None
def parse_date(v):
return temporal_parser(v, dt.date.fromisoformat)
def parse_datetime(v):
return temporal_parser(v, dt.datetime.fromisoformat)
def parse_time(v):
return temporal_parser(v, dt.time.fromisoformat)
utc = dt.timezone.utc
CAN_PARSE_TEMPORAL = True
__version_info__ = "1.0.0"
__version__ = "1.0.0"
version = "1.0.0"
VERSION = "1.0.0"
def get_version():
# type: () -> Text
return version
__all__ = [
"EnvironmentCastError",
"EnvironmentDefaultError",
"Environment",
"get_version",
"env",
]
logger = logging.getLogger(__name__)
class EnvironmentCastError(ValueError):
"""
Raised by EnvironmentCaster when one of the utility methods cannot proceed
with the incoming data.
"""
class EnvironmentDefaultError(ValueError):
"""
Raised by Environment when a default value is provided and it's not
a stringy example.
"""
class EnvironmentCaster(object):
"""
Provides utilities to cast a raw string value to a more appropriate type.
Each method accepts a single stringy value, so that the method may be used
on iterables etc.
"""
__slots__ = ()
timedelta_re = re.compile(
r"(?P<days>-?[0-9]{1,})\s*(?:d|dys?|days?)"
r"|"
r"(?P<seconds>-?[0-9]{1,})\s*(?:s|secs?|seconds?)"
r"|"
r"(?P<microseconds>-?[0-9]{1,})\s*(?:us?|µs?|microsecs?|microseconds?)"
r"|"
r"(?P<milliseconds>-?[0-9]{1,})\s*(?:ms|millisecs?|milliseconds?)"
r"|"
r"(?P<minutes>-?[0-9]{1,})\s*(?:m|mins?|minutes?)"
r"|"
r"(?P<hours>-?[0-9]{1,})\s*(?:h|hrs?|hours?)"
r"|"
r"(?P<weeks>-?[0-9]{1,})\s*(?:w|wks?|weeks?)",
flags=re.UNICODE | re.IGNORECASE,
)
timedelta_str_re = re.compile(
r"(?:(?P<days>-?[0-9]{1,})\s*(?:d|dys?|days?),?\s*)?"
r"(?P<hours>[0-9]{1,})"
r":"
r"(?P<minutes>[0-9]{2})"
r":"
r"(?P<seconds>[0-9]{2})"
r"(?:\.(?P<microseconds>[0-9]{1,6}))?",
flags=re.UNICODE | re.IGNORECASE,
)
def text(self, value):
# type: (Text) -> Text
sq = "'"
dq = '"'
if len(value) <= 1:
return value
elif value[0] == sq and value[-1] == sq:
value = value[1:-1]
elif value[0] == dq and value[-1] == dq:
value = value[1:-1]
if value.lstrip() != value:
value = value.lstrip()
elif value.rstrip() != value:
value = value.rstrip()
return value
def int(self, value):
# type: (Text) -> int
try:
return int(value)
except ValueError as e:
raise EnvironmentCastError(str(e))
def boolean(self, value):
# type: (Text) -> bool
value = value.lower().strip()
good_values = ("true", "on", "y", "yes", "1")
bad_values = ("false", "off", "n", "no", "0", "")
if value in good_values:
return True
elif value in bad_values:
return False
zipped_up = zip(good_values, bad_values)
options = ("/".join(x) for x in zipped_up)
paired = ", ".join(options)
raise EnvironmentCastError(
"Failed to read as a boolean. Got value {0!r}. Expected one of: {1!s}".format(
value, paired
)
)
bool = boolean
def uuid(self, value):
# type: (Text) -> uuid.UUID
value = value.lower().strip()
try:
return uuid.UUID(value)
except ValueError:
raise EnvironmentCastError(
"Cannot create uuid from unrecognised value {0!r}".format(value)
)
def datetime(self, value):
# type: (Text) -> dt.datetime
parsed_value = parse_datetime(value) # type: Optional[dt.datetime]
if parsed_value is not None:
return parsed_value
del parsed_value
try:
return dt.datetime.strptime(value, "%Y-%m-%d")
except ValueError as e:
raise EnvironmentCastError(
"Cannot create datetime from unrecognised value {0!r}, {1!s}".format(
value, e
)
)
def date(self, value):
# type: (Text) -> dt.date
try:
parsed_value = parse_date(value) # type: Optional[dt.date]
except ValueError as e:
raise EnvironmentCastError(
"Cannot create date from unrecognised value {0!r}, {1!s}".format(
value, e
)
)
if parsed_value is not None:
return parsed_value
raise EnvironmentCastError(
"Could not parse value {0!r} into a datetime.date".format(value)
)
def time(self, value):
# type: (Text) -> dt.time
parsed_value = parse_time(value) # type: Optional[dt.time]
if parsed_value is not None:
return parsed_value
raise EnvironmentCastError(
"Could not parse value {0!r} into a datetime.time".format(value)
)
def _just_timedelta(self, value):
# type: (Text) -> dt.timedelta
kwargs = {
"days": 0,
"seconds": 0,
"microseconds": 0,
"milliseconds": 0,
"minutes": 0,
"hours": 0,
"weeks": 0,
}
timedelta_str = self.timedelta_str_re.match(value)
if timedelta_str:
# Parsing the output of str(timedelta(...))
for match_kwarg, match_value in timedelta_str.groupdict().items():
if match_value is not None:
kwargs[match_kwarg] = self.int(match_value)
else:
for match in self.timedelta_re.finditer(value):
for match_kwarg, match_value in match.groupdict().items():
if match_value is not None:
kwargs[match_kwarg] = self.int(match_value)
if {*kwargs.values()} == {0}:
raise EnvironmentCastError(
"Failed to parse any positive/negative components from timedelta string"
)
return dt.timedelta(**kwargs)
def timedelta(self, value):
# type: (Text) -> dt.timedelta
if "=" in value:
# should be be "1, 2, weeks=1" or "days=3, x=4"
args, kwargs = self._guess_and_convert_string_to_arguments(value)
# I can't use inspect.signature, I think because timedelta doesn't
# implement __text_signature__
try:
return dt.timedelta(*args, **kwargs)
except TypeError as exc:
raise EnvironmentCastError(
f"Unable to convert stringified arguments representation into timedelta"
)
elif ";" in value or ":" in value:
# we know for sure it's '1 week; 2 days; 3 seconds'
# or '1 day, 6:10:12'
return self._just_timedelta(value)
else:
# The format might be '1 week, 2 days, 3 minutes' or it could be
# '1, 2, 3' as plain arguments.
try:
return self._just_timedelta(value)
except EnvironmentCastError:
# it's probably '1, 2, 3, 4'
args, kwargs = self._guess_and_convert_string_to_arguments(value)
# I can't use inspect.signature, I think because timedelta doesn't
# implement __text_signature__
try:
return dt.timedelta(*args, **kwargs)
except TypeError as exc:
raise EnvironmentCastError(
f"Unable to convert stringified arguments representation into timedelta"
)
def email(self, value):
# type: (Text) -> Text
if "@" not in value:
raise EnvironmentCastError(
"Could not parse value {0!r} as an email address; missing @".format(
value
)
)
if value.count("@") > 1:
raise EnvironmentCastError(
"Could not parse value {0!r} as an email address; multiple @ symbols".format(
value
)
)
if len(value) < 3:
raise EnvironmentCastError(
"Could not parse value {0!r} as an email address; should be at least a@b, right?".format(
value
)
)
if value[0] == "@" or value[-1] == "@":
raise EnvironmentCastError(
"Could not parse value {0!r} as an email address; starts or ends with @".format(
value
)
)
return value
def hex(self, value):
# type: (Text) -> Text
try:
int(value, 16)
except ValueError as e:
for index, bit in enumerate(value, start=1):
if bit not in string.hexdigits:
msg = "Could not parse value {0!r} as hex, first invalid character is {1!r} at position {2}".format(
value, bit, index
)
raise EnvironmentCastError(msg)
return value
def b64(self, value):
# type: (Union[bytes, Text]) -> Union[bytes, Text]
try:
base64.urlsafe_b64decode(value)
except (TypeError, binascii.Error) as e:
try:
base64.standard_b64decode(value)
except (TypeError, binascii.Error) as e:
raise EnvironmentCastError(
"Could not parse value {0!r} as URL-safe or normal base64 encoded data, {1!s}".format(
value, e
)
)
return value
def importable(self, value):
# type: (Text) -> Text
if value[0] == "." or value[-1] == ".":
raise EnvironmentCastError(
"Could not parse value {0!r} as an importable, starts/ends with '.'".format(
value
)
)
parts = value.split(".")
for part in parts:
# py3
if hasattr(part, "isidentifier"):
if part.isidentifier() is False:
raise EnvironmentCastError(
"Invalid importable path component {0!r} in {1!r}".format(
part, value
)
)
# py2, slower...
else:
if not re.match(tokenize.Name, part): # type: ignore
raise EnvironmentCastError(
"Invalid importable path component {0!r} in {1!r}".format(
part, value
)
)
return value
def filepath(self, value):
# type: (Text) -> Text
if not os.path.exists(value):
raise EnvironmentCastError("Could not locate file {0!r}".format(value))
if not os.path.isfile(value):
raise EnvironmentCastError(
"Located {0!r} but it's not a file".format(value)
)
try:
fp = open(value, "r")
except IOError as e:
raise EnvironmentCastError(
"Cannot open file {0!r} for reading".format(value)
)
else:
fp.close()
return value
def directory(self, value):
# type: (Text) -> Text
if not os.path.exists(value):
raise EnvironmentCastError("Could not locate directory {0!r}".format(value))
if not os.path.isdir(value):
raise EnvironmentCastError(
"Located {0!r} but it's not a directory".format(value)
)
return value
def web_address(self, value):
# type: (Text) -> Text
if (
value[0:7] == "http://"
or value[0:8] == "https://"
or value[0:2] == "//"
or (value[0] == "/" and value[1] != "/")
):
return value
raise EnvironmentCastError(
"Could not parse {0!r} as a URL, expected it to be either absolute (http://www.example.com, https://www.example.com) or scheme-relative (//www.example.com/path), or host relative (/path)".format(
value
)
)
def decimal(self, value):
# type: (Text) -> decimal.Decimal
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
msg = "Could not parse value {0!r} into a decimal".format(value)
raise EnvironmentCastError(msg)
def json(self, value):
# type: (Text) -> Any
try:
return json.loads(value)
except json.JSONDecodeError:
if len(value) > 13:
example = "{0!s}...".format(value[0:10])
else:
example = value
raise EnvironmentCastError(
"Could not parse value {0!r} as JSON".format(example)
)
def _guess_and_convert_string_to_arguments(self, value):
# type: (Text) -> Tuple[Tuple, Dict[Text, Any]]
parts = [part.strip() for part in value.split(",") if part.strip()]
args, kwargs = (), {}
types = (
self.int,
self.datetime,
self.date,
self.time,
self.decimal,
self.uuid,
self.bool,
# text based fallbacks.
self.email,
self.hex,
self.b64,
self.filepath,
self.directory,
self.importable,
self.web_address,
self.json,
)
for part in parts:
param_name, sep, param_value = part.partition("=")
if not sep:
for converter in types:
try:
converted = converter(part)
except EnvironmentCastError:
continue
else:
args += (converted,)
logger.debug("Converted %s using %s", part, converter)
break
else:
value = param_value.strip()
for converter in types:
try:
converted = converter(value)
except EnvironmentCastError:
continue
else:
kwargs[param_name.strip()] = converted
logger.debug(
"Converted %s using %s",
param_name.strip(),
converter,
)
break
return args, kwargs
class Environment(object):
"""
Wrapper over os.environ which provides convenience methods for fetching
various data types (including iterables) in a hopefully sensible way.
Also keeps track of those keys it has seen, along with the defaults/examples
for those, so that they may be output as documentation.
"""
__slots__ = ("source", "used", "fallbacks", "ensure")
def __init__(self, source):
# type: (Mapping[Text, Text]) -> None
self.source = source
self.used = set() # type: Set[Tuple[Text, Text]]
self.fallbacks = set() # type: Set[Tuple[Text, Text]]
self.ensure = EnvironmentCaster()
def __repr__(self): # type: ignore
used = {x[0] for x in self.used}
fallbacks = {x[0] for x in self.fallbacks}
return "<Environment: from source={0}, from defaults={1}>".format(
sorted(used), sorted(fallbacks)
)
def __str__(self): # type: ignore
used = {x[0] for x in self.used}
return ", ".join(sorted(used))
def __bool__(self):
# type: () -> bool
return bool(self.used)
def __iter__(self):
# type: () -> Iterator[Tuple[Text, Text, bool]]
used = ((name, example, True) for name, example in self.used)
fallbacks = ((name, example, False) for name, example in self.fallbacks)
all_together = list(itertools.chain(used, fallbacks))
all_together = sorted(all_together, key=operator.itemgetter(0))
return iter(all_together)
def __contains__(self, item):
# type: (Text) -> bool
return item in self.source
def print(self, format="export {key!s}='{value!s}'", stream=None):
# type: (Text, TextIOBase) -> None
stream = stream or sys.stdout
try:
from django.views.debug import SafeExceptionReporterFilter
HIDDEN_SETTINGS = SafeExceptionReporterFilter.hidden_settings
CLEANSED_SUBSTITUTE = SafeExceptionReporterFilter.cleansed_substitute
except ImportError:
try:
from django.views.debug import HIDDEN_SETTINGS, CLEANSED_SUBSTITUTE
except ImportError:
HIDDEN_SETTINGS = re.compile(
"API|TOKEN|KEY|SECRET|PASS|SIGNATURE", flags=re.I
)
CLEANSED_SUBSTITUTE = "********************"
if not format.endswith(os.linesep):
format = format + os.linesep
for env_var, env_example, read_from_env in self:
if HIDDEN_SETTINGS.search(env_var):
env_example = CLEANSED_SUBSTITUTE
stream.write(format.format(key=env_var, value=env_example))
def raw(self, key, default=""):
# type: (Text, Text) -> Text
if not isinstance(default, string_types):
msg = "default value for {0} should be a string, so that parsing is consistent and there's a valid example value".format(
key
)
raise EnvironmentDefaultError(msg)
try:
value = self.source[key] # type: str
self.used.add((key, default))
except KeyError:
logger.debug("Failed to read %s, using default", key)
value = default
self.fallbacks.add((key, default))
return value
def _tidy_raw_string(self, key, value):
# type: (Text, Text) -> Text
tidied = self.ensure.text(value)
if tidied != value:
logger.debug("Stripped surrounding quotes from %s", key)
return tidied
def not_implemented(self, key, default=""):
# type: (Text, Text) -> None
raise NotImplementedError("Won't handle this datatype")
def text(self, key, default):
# type: (Text, Text) -> Text
value = self.raw(key, default)
value = self._tidy_raw_string(key, value)
return value
str = text
unicode = text
def int(self, key, default):
# type: (Text, Text) -> int
value = self.text(key, default)
return self.ensure.int(value)
def boolean(self, key, default):
# type: (Text, Text) -> bool
value = self.text(key, default)
return self.ensure.boolean(value)
bool = boolean
def uuid(self, key, default):
# type: (Text, Text) -> uuid.UUID
value = self.text(key, default)
return self.ensure.uuid(value)
def datetime(self, key, default):
# type: (Text, Text) -> dt.datetime
value = self.text(key, default)
return self.ensure.datetime(value)
def date(self, key, default):
# type: (Text, Text) -> dt.date
value = self.text(key, default)
return self.ensure.date(value)
def time(self, key, default):
# type: (Text, Text) -> dt.time
value = self.text(key, default)
return self.ensure.time(value)
def timedelta(self, key, default):
# type: (Text, Text) -> dt.timedelta
value = self.text(key, default)
return self.ensure.timedelta(value)
def email(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.email(value)
def hex(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.hex(value)
def b64(self, key, default):
# type: (Text, Text) -> Union[bytes, Text]
value = self.text(key, default)
return self.ensure.b64(value)
def decimal(self, key, default):
# type: (Text, Text) -> decimal.Decimal
value = self.text(key, default)
return self.ensure.decimal(value)
def importable(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.importable(value)
def filepath(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.filepath(value)
def directory(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.directory(value)
def web_address(self, key, default):
# type: (Text, Text) -> Text
value = self.text(key, default)
return self.ensure.web_address(value)
def django_database_url(self, key="", default=""):
# type: (Text, Text) -> Dict[Text, Union[boolean, int, Text, Dict[Text, Text]]]
# Facilitate swapping, so that you can do the following:
# env.django_database_url("sqlite://:memory:") and have it
# successfully read the value from the database.
# or alternatively do:
# env.django_database_url("MY_DB")
# which won't give you a default value ...
if default == "":
if key == "":
key = "DATABASE_URL"
elif "://" in key:
default = key
key = "DATABASE_URL"
elif key == "":
key = "DATABASE_URL"
if not default:
raise TypeError("{cls}.django_database_url() missing 1 required argument: 'default'".format(cls=self.__class__.__name__))
aliases = {
"postgre": "postgres",
"postgregis": "postgis",
"postgresql": "postgres",
"postgresqlgis": "postgis",
"psycopg2": "postgres",
"psycopg2gis": "postgis",
"psql": "postgres",
"psqlgis": "postgis",
"pgsql": "postgres",
"pgsqlgis": "postgis",
"pg": "postgres",
"pggis": "postgis",
"pgis": "postgis",
"mariadb": "mysql",
"maria": "mysql",
"mariadbgis": "mysqlgis",
"mariagis": "mysqlgis",
"mysqlclient": "mysql",
"mysqlclientgis": "mysqlgis",
"sqlite3": "sqlite",
"mysql-connector": "mysqlconnector",
"mysql-connecter": "mysqlconnector",
"mysql_connector": "mysqlconnector",
"mysql_connecter": "mysqlconnector",
"awsredshift": "redshift",
"aws_redshift": "redshift",
"aws-redshift": "redshift",
"ldapdb": "ldap",
}
builtin_scheme_map = {
"postgres": "django.db.backends.postgresql",
"mysql": "django.db.backends.mysql",
"sqlite": "django.db.backends.sqlite3",
"mysqlconnector": "mysql.connector.django",
"redshift": "django_redshift_backend",
"oracle": "django.db.backends.oracle",
"mssql": "mssql", # https://github.com/microsoft/mssql-django
"ldap": "ldapdb.backends.ldap", # https://github.com/django-ldapdb/django-ldapdb
"mysqlgis": "django.contrib.gis.db.backends.mysql",
"postgis": "django.contrib.gis.db.backends.postgis",
}
def int_or_none(item_to_convert):
try:
return self.ensure.int(item_to_convert)
except EnvironmentCastError as exc:
if item_to_convert.strip().lower() == "none":
return None
raise EnvironmentCastError(str(exc))
global_options = {
"ATOMIC_REQUESTS": self.ensure.boolean,
"AUTOCOMMIT": self.ensure.boolean,
"CONN_MAX_AGE": int_or_none,
"TIME_ZONE": self.ensure.text,
"DISABLE_SERVER_SIDE_CURSORS": self.ensure.boolean,
"CHARSET": self.ensure.text,
"COLLATION": self.ensure.text,
"MIGRATE": self.ensure.boolean,
"TEMPLATE": self.ensure.text,
}
value = self.text(key, default)
result = urlparse(value)
# scheme, netloc, path, params, query, fragment = result
if result.scheme in builtin_scheme_map:
engine = builtin_scheme_map[result.scheme]
elif result.scheme in aliases:
result_scheme = aliases[result.scheme]
engine = builtin_scheme_map[result_scheme]
else:
# dotted path to selected engine.
engine = env.ensure.importable(result.scheme)
path = result.path[1:]
host, port = result._hostinfo
if engine == "django.db.backends.sqlite3":
# It got parsed as the port part, so it's missing the colon prefix
if port == "memory:":
if result.path and result.path != "/":
raise EnvironmentCastError(
f"Unexpected path ({result.path}) for an in-memory SQLite database"
)
path = ":memory:"
port = None
host = None
# empty = memory, for compatibility with django-environ & dj-database-url
# which apparently do it for sqlalchemy:
# https://github.com/joke2k/django-environ/blob/44ac6649ad6135ff4246371880298bf732cd1c52/environ/environ.py#L487-L492
# https://github.com/jacobian/dj-database-url/blob/1937ed9e61d273163353c8546825dd529ce8546c/dj_database_url.py#L98-L101
elif path == "":
path = ":memory:"
port = None
host = None
# Complex case for postgres family stuff, for compatibility with
# django-environ
# https://github.com/joke2k/django-environ/blob/44ac6649ad6135ff4246371880298bf732cd1c52/environ/environ.py#L513-L517
elif path and path[0] == "/":
if "cloudsql" in path or engine in {
"django.db.backends.postgresql",
"django.contrib.gis.db.backends.postgis",
}:
host, path = path.rsplit("/", 1)
# Special-case for oracle.
# https://github.com/joke2k/django-environ/blob/44ac6649ad6135ff4246371880298bf732cd1c52/environ/environ.py#L519-L521
elif engine == "django.db.backends.oracle" and not path:
path = host
host = None
# Special-case LDAP, fo compatibility with django-environ
# https://github.com/joke2k/django-environ/blob/44ac6649ad6135ff4246371880298bf732cd1c52/environ/environ.py#L496-L502
elif engine == "ldapdb.backends.ldap":
path = "{}://{}".format(result.scheme, host)
if port:
path += ":{}".format(port)
parsed_config = {
"ENGINE": engine,
"NAME": unquote(path),
"OPTIONS": {},
}
if result.username:
parsed_config["USER"] = unquote(self.ensure.text(result.username))
if result.password:
parsed_config["PASSWORD"] = unquote(self.ensure.text(result.password))
if host:
parsed_config["HOST"] = unquote(self.ensure.text(host))
if port:
parsed_config["PORT"] = env.ensure.int(unquote(self.ensure.text(port)))
# query string is both global options and OPTIONS, for compatibility
# with things like django-environ
if result.query:
for key, value in parse_qsl(result.query):
capkey = key.upper()
value = unquote(value)
if capkey in global_options:
converter = global_options[capkey]
parsed_config.update({capkey: converter(value)})
else:
parsed_config["OPTIONS"].update({key: self.ensure.text(value)})
# if given a fragment, those are all global options.
if result.fragment:
for key, value in parse_qsl(result.fragment):
capkey = key.upper()
if capkey in parsed_config:
raise EnvironmentCastError(
f"fragment key ({key}) conflicts with previously set query-string key ({capkey})"
)
value = unquote(value)
if capkey in global_options:
converter = global_options[capkey]
parsed_config.update({capkey: converter(value)})
else:
parsed_config.update({key: self.ensure.text(value)})
# Special case, setting the ssl-ca into a nested dictionary
# for compatibility with dj-database-url
# https://github.com/jacobian/dj-database-url/blob/1937ed9e61d273163353c8546825dd529ce8546c/dj_database_url.py#L133-L135
if "ssl-ca" in parsed_config["OPTIONS"] and engine in {
"django.db.backends.mysql",
"django.contrib.gis.db.backends.mysql",
}:
keypath = parsed_config["OPTIONS"].pop("ssl-ca")
parsed_config["OPTIONS"].setdefault("ssl", {})
parsed_config["OPTIONS"]["ssl"]["ca"] = self.ensure.text(keypath)
# Special-case, append the search path if currentSchema is given for a
# postgres based engine. For compatibility with dj-database-url
# https://github.com/jacobian/dj-database-url/blob/1937ed9e61d273163353c8546825dd529ce8546c/dj_database_url.py#L142-L149
# https://stackoverflow.com/questions/51360469/django-postgresql-set-statement-timeout
# https://www.postgresql.org/docs/9.6/libpq-connect.html#LIBPQ-PARAMKEYWORDS
# https://www.postgresql.org/docs/9.2/config-setting.html#CONFIG-SETTING-OTHER-METHODS
if "currentSchema" in parsed_config["OPTIONS"] and engine in {
"django.db.backends.postgresql",
"django.contrib.gis.db.backends.postgis",
"django_redshift_backend",
}:
schema = parsed_config["OPTIONS"].pop("currentSchema")
parsed_config["OPTIONS"].setdefault("options", "")
parsed_config["OPTIONS"]["options"] += " -c search_path={!s}".format(schema)
parsed_config["OPTIONS"]["options"] = parsed_config["OPTIONS"][
"options"
].strip()
return parsed_config
def _tidy_iterable(self, key, value, converter=None):
# type: (Text, Text, Optional[Callable[..., Any]]) -> Iterable[Any]
paren_l, paren_r = "(", ")"
sq_l, sq_r = "[", "]"
cb_l, cb_r = "{", "}"
if len(value) > 1:
if value[0] == paren_l and value[-1] == paren_r:
logger.debug("Stripped surrounding tuple identifiers from %s", key)
value = value[1:-1]
elif value[0] == sq_l and value[-1] == sq_r:
logger.debug("Stripped surrounding list identifiers from %s", key)
value = value[1:-1]
elif value[0] == cb_l and value[-1] == cb_r:
logger.debug(
"Stripped surrounding set-literal identifiers from %s", key
)
value = value[1:-1]