|
| 1 | +import os |
| 2 | +import pickle |
| 3 | +import zlib |
1 | 4 | from datetime import datetime, timedelta, timezone, tzinfo
|
| 5 | +from pathlib import Path |
2 | 6 |
|
3 | 7 | import regex as re
|
4 | 8 |
|
@@ -84,8 +88,46 @@ def get_local_tz_offset():
|
84 | 88 | return offset
|
85 | 89 |
|
86 | 90 |
|
87 |
| -_search_regex_parts = [] |
88 |
| -_tz_offsets = list(build_tz_offsets(_search_regex_parts)) |
89 |
| -_search_regex = re.compile("|".join(_search_regex_parts)) |
90 |
| -_search_regex_ignorecase = re.compile("|".join(_search_regex_parts), re.IGNORECASE) |
91 | 91 | local_tz_offset = get_local_tz_offset()
|
| 92 | + |
| 93 | +_tz_offsets = None |
| 94 | +_search_regex = None |
| 95 | +_search_regex_ignorecase = None |
| 96 | + |
| 97 | + |
| 98 | +def _load_offsets(cache_path, current_hash): |
| 99 | + global _tz_offsets, _search_regex, _search_regex_ignorecase |
| 100 | + |
| 101 | + try: |
| 102 | + with open(cache_path, mode="rb") as file: |
| 103 | + ( |
| 104 | + serialized_hash, |
| 105 | + _tz_offsets, |
| 106 | + _search_regex, |
| 107 | + _search_regex_ignorecase, |
| 108 | + ) = pickle.load(file) |
| 109 | + if current_hash is None or current_hash == serialized_hash: |
| 110 | + return |
| 111 | + except (FileNotFoundError, ValueError, TypeError): |
| 112 | + pass |
| 113 | + |
| 114 | + _search_regex_parts = [] |
| 115 | + _tz_offsets = list(build_tz_offsets(_search_regex_parts)) |
| 116 | + _search_regex = re.compile("|".join(_search_regex_parts)) |
| 117 | + _search_regex_ignorecase = re.compile("|".join(_search_regex_parts), re.IGNORECASE) |
| 118 | + |
| 119 | + with open(cache_path, mode="wb") as file: |
| 120 | + pickle.dump( |
| 121 | + (current_hash, _tz_offsets, _search_regex, _search_regex_ignorecase), |
| 122 | + file, |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +CACHE_PATH = Path(__file__).parent.joinpath("data", "dateparser_tz_cache.pkl") |
| 127 | + |
| 128 | +if "BUILD_TZ_CACHE" in os.environ: |
| 129 | + current_hash = zlib.crc32(str(timezone_info_list).encode("utf-8")) |
| 130 | +else: |
| 131 | + current_hash = None |
| 132 | + |
| 133 | +_load_offsets(CACHE_PATH, current_hash) |
0 commit comments