rotools 0.1.145__tar.gz

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 (46) hide show
  1. rotools-0.1.145/LICENSE +201 -0
  2. rotools-0.1.145/PKG-INFO +49 -0
  3. rotools-0.1.145/README.md +27 -0
  4. rotools-0.1.145/ROTools/Config/Config.py +53 -0
  5. rotools-0.1.145/ROTools/Config/ConfigLoader.py +73 -0
  6. rotools-0.1.145/ROTools/Config/__init__.py +0 -0
  7. rotools-0.1.145/ROTools/Helpers/Attr.py +55 -0
  8. rotools-0.1.145/ROTools/Helpers/CoordinatesGPS.py +10 -0
  9. rotools-0.1.145/ROTools/Helpers/Info.py +19 -0
  10. rotools-0.1.145/ROTools/Helpers/RedisSingletonLock.py +22 -0
  11. rotools-0.1.145/ROTools/Helpers/RequestHelper.py +32 -0
  12. rotools-0.1.145/ROTools/Helpers/SignalHandler.py +30 -0
  13. rotools-0.1.145/ROTools/Helpers/StopWatch.py +39 -0
  14. rotools-0.1.145/ROTools/Helpers/WorkersCollection.py +69 -0
  15. rotools-0.1.145/ROTools/Helpers/__init__.py +0 -0
  16. rotools-0.1.145/ROTools/Helpers/db_helpers.py +32 -0
  17. rotools-0.1.145/ROTools/Helpers/df_helpers.py +22 -0
  18. rotools-0.1.145/ROTools/Helpers/marshmallow_helpers.py +19 -0
  19. rotools-0.1.145/ROTools/Helpers/text_helpers.py +24 -0
  20. rotools-0.1.145/ROTools/Helpers/time_helpers.py +13 -0
  21. rotools-0.1.145/ROTools/Wrappers/MinioWrapper.py +90 -0
  22. rotools-0.1.145/ROTools/Wrappers/PathWrapper.py +51 -0
  23. rotools-0.1.145/ROTools/Wrappers/SFTPWrapper.py +40 -0
  24. rotools-0.1.145/ROTools/Wrappers/__init__.py +0 -0
  25. rotools-0.1.145/ROTools/__init__.py +0 -0
  26. rotools-0.1.145/ROTools/core/DictObj.py +113 -0
  27. rotools-0.1.145/ROTools/core/DumpBase.py +74 -0
  28. rotools-0.1.145/ROTools/core/HashBuilder.py +39 -0
  29. rotools-0.1.145/ROTools/core/RateLimiter.py +20 -0
  30. rotools-0.1.145/ROTools/core/SleepController.py +16 -0
  31. rotools-0.1.145/ROTools/core/SmartCounter.py +17 -0
  32. rotools-0.1.145/ROTools/core/StringBuilder.py +31 -0
  33. rotools-0.1.145/ROTools/core/__init__.py +0 -0
  34. rotools-0.1.145/ROTools/dao/BaseDao.py +15 -0
  35. rotools-0.1.145/ROTools/dao/LastTimeDao.py +20 -0
  36. rotools-0.1.145/ROTools/dao/TaskDao.py +23 -0
  37. rotools-0.1.145/ROTools/dao/__init__.py +0 -0
  38. rotools-0.1.145/ROTools/logs/ShortNameFilter.py +7 -0
  39. rotools-0.1.145/ROTools/logs/__init__.py +0 -0
  40. rotools-0.1.145/ROTools.egg-info/PKG-INFO +49 -0
  41. rotools-0.1.145/ROTools.egg-info/SOURCES.txt +49 -0
  42. rotools-0.1.145/ROTools.egg-info/dependency_links.txt +1 -0
  43. rotools-0.1.145/ROTools.egg-info/requires.txt +2 -0
  44. rotools-0.1.145/ROTools.egg-info/top_level.txt +1 -0
  45. rotools-0.1.145/setup.cfg +13 -0
  46. rotools-0.1.145/setup.py +18 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: rotools
3
+ Version: 0.1.145
4
+ Summary: Robert Olechowski python tools
5
+ Home-page: https://github.com/RobertOlechowski/ROTools
6
+ Author: Robert Olechowski
7
+ Author-email: robertolechowski@gmail.com
8
+ Requires-Python: >=3.13
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: PyYAML>=6.0.3
12
+ Requires-Dist: humanize>=4.14.0
13
+ Dynamic: author
14
+ Dynamic: author-email
15
+ Dynamic: description
16
+ Dynamic: description-content-type
17
+ Dynamic: home-page
18
+ Dynamic: license-file
19
+ Dynamic: requires-dist
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ # Description
24
+ ..........................
25
+
26
+
27
+ # Todo:
28
+ - update build config to pyproject.toml
29
+ - Add Merge command in DictObj
30
+
31
+ # Build on Windows in Pycharm
32
+ ```
33
+ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
34
+ ```
35
+
36
+ ```
37
+ python setup.py sdist
38
+ rm .\dist\*
39
+ python -m build
40
+ twine upload dist/*
41
+ ```
42
+
43
+
44
+ # Notes
45
+ - .\tools\build.ps1
46
+ - pip install --upgrade ROTools
47
+
48
+
49
+
@@ -0,0 +1,27 @@
1
+ # Description
2
+ ..........................
3
+
4
+
5
+ # Todo:
6
+ - update build config to pyproject.toml
7
+ - Add Merge command in DictObj
8
+
9
+ # Build on Windows in Pycharm
10
+ ```
11
+ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
12
+ ```
13
+
14
+ ```
15
+ python setup.py sdist
16
+ rm .\dist\*
17
+ python -m build
18
+ twine upload dist/*
19
+ ```
20
+
21
+
22
+ # Notes
23
+ - .\tools\build.ps1
24
+ - pip install --upgrade ROTools
25
+
26
+
27
+
@@ -0,0 +1,53 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from ROTools.Helpers.Attr import setattr_ex, getattr_ex
5
+ from ROTools.core.DictObj import DictObj
6
+
7
+ class Config(DictObj):
8
+ def __init__(self, parent):
9
+ super().__init__(parent)
10
+
11
+ def process_secrets(self, secrets_config):
12
+ import yaml
13
+ if secrets_config is None:
14
+ return
15
+
16
+ if isinstance(secrets_config.files, str):
17
+ secrets_config.files = [secrets_config.files]
18
+
19
+ secrets = None
20
+ for item in secrets_config.files:
21
+ if Path(item).exists():
22
+ secrets = DictObj(yaml.safe_load(open(item)))
23
+ break
24
+
25
+ if secrets is None:
26
+ return
27
+
28
+ for item in secrets_config.targets:
29
+ value_name = item.get("value") or item.name
30
+ value = secrets.get(value_name, None)
31
+
32
+ if self.has(item.name) and value is not None:
33
+ self.set(item.name, value)
34
+
35
+ def add_env_data(self, prefix):
36
+ extra_config = [(key[len(prefix):].lower(), value) for key, value in os.environ.items() if key.startswith(prefix)]
37
+
38
+ for key, value in extra_config:
39
+ _old_value = getattr_ex(self, key)
40
+ if _old_value is not None and isinstance(_old_value, bool):
41
+ setattr_ex(self, key, value in ["true", "True", "TRUE", "1", ])
42
+ continue
43
+
44
+ if _old_value is not None and isinstance(_old_value, int):
45
+ setattr_ex(self, key, int(value))
46
+ continue
47
+
48
+ if _old_value is not None and isinstance(_old_value, float):
49
+ setattr_ex(self, key, float(value))
50
+ continue
51
+
52
+ if _old_value is not None:
53
+ setattr_ex(self, key, value)
@@ -0,0 +1,73 @@
1
+ import os
2
+
3
+ from ROTools.Config.Config import Config
4
+ from ROTools.core.DictObj import DictObj
5
+
6
+
7
+ def load_config(config_file):
8
+ import yaml
9
+ return Config(DictObj(yaml.safe_load(open(config_file))))
10
+
11
+ def load_config_directory(directory, config_file):
12
+ import yaml
13
+ files = os.listdir(directory)
14
+ files = [a for a in files if not a.startswith("_")]
15
+ files = [file for file in files if os.path.isfile(os.path.join(directory, file))]
16
+ files = [os.path.join(directory, a) for a in files if a.endswith(('.yaml', '.yml'))]
17
+
18
+ main_file_name = os.path.join(directory, config_file)
19
+ if main_file_name not in files:
20
+ raise Exception("Config file not found!")
21
+
22
+ files = [a for a in files if a != main_file_name]
23
+
24
+ config = Config(DictObj(yaml.safe_load(open(main_file_name))))
25
+
26
+ for file in files:
27
+ sub_config = DictObj(yaml.safe_load(open(file)))
28
+ for key, value in sub_config.items():
29
+ config.set(key, value)
30
+
31
+ return config
32
+
33
+ def process_services(config):
34
+ from pathlib import Path
35
+ from ROTools.core.DictObj import DictObj
36
+ import yaml
37
+
38
+ if not config.has("services.config_files"):
39
+ return
40
+
41
+ files = [Path(a) for a in config.get("services.config_files", [])]
42
+ files = [a for a in files if a.exists()]
43
+ if len(files) == 0:
44
+ raise Exception("No services config files found!")
45
+
46
+ config.services.rem("config_files")
47
+
48
+ services = DictObj(yaml.safe_load(open(files[0])))
49
+
50
+ for key, value in [(a, b) for a, b in services.items() if b.has("ref_name")]:
51
+ service_config = services.get(value.ref_name, throw=True)
52
+
53
+ value.rem("ref_name", throw=False)
54
+
55
+ for key2, value2 in service_config.items():
56
+ value.set(key2, value2)
57
+
58
+
59
+ for key, value in config.services.items():
60
+ ref_name = value if isinstance(value, str) else value.get("ref_name")
61
+ if ref_name is None:
62
+ continue
63
+ service_config = services.get(ref_name, throw=True)
64
+ if isinstance(value, DictObj):
65
+ value.rem("ref_name")
66
+
67
+ if isinstance(value, str):
68
+ value = DictObj()
69
+ config.services.set(key, value)
70
+
71
+ for key2, value2 in service_config.items():
72
+ value.set(key2, value2)
73
+
File without changes
@@ -0,0 +1,55 @@
1
+ def _split_name(name):
2
+ if isinstance(name, str):
3
+ return name.split(".")
4
+
5
+ if not isinstance(name, list):
6
+ raise Exception("Param error")
7
+
8
+ return name
9
+
10
+ def getattr_ex(_obj, name, default=None):
11
+ name = _split_name(name)
12
+
13
+ for item in name:
14
+ if _obj is None:
15
+ return default
16
+ _obj = getattr(_obj, item, None)
17
+ return _obj
18
+
19
+ def setattr_ex(_obj, name, value, parent_class=object):
20
+ name = _split_name(name)
21
+
22
+ for item in name[:-1]:
23
+ _next = getattr(_obj, item, None)
24
+ if _next is None:
25
+ _next = parent_class()
26
+ setattr(_obj, item, _next)
27
+ _obj = _next
28
+ setattr(_obj, name[-1], value)
29
+
30
+ def hasattr_ex(_obj, name):
31
+ name = _split_name(name)
32
+
33
+ for i, item in enumerate(name):
34
+ is_last = i == len(name) - 1
35
+ if hasattr(_obj, item) is False:
36
+ return False
37
+ _obj = getattr(_obj, item, None)
38
+ if _obj is None and not is_last:
39
+ return False
40
+ return True
41
+
42
+ def delattr_ex(_obj, name):
43
+ name = _split_name(name)
44
+
45
+ for i, item in enumerate(name):
46
+ is_last = i == len(name) - 1
47
+ if is_last:
48
+ delattr(_obj, item)
49
+ return
50
+ _obj = getattr(_obj, item, None)
51
+ if _obj is None:
52
+ return
53
+
54
+
55
+
@@ -0,0 +1,10 @@
1
+ class CoordinatesGPS:
2
+ def __init__(self, latitude, longitude):
3
+ self.latitude = float(latitude)
4
+ self.longitude = float(longitude)
5
+
6
+ def __str__(self):
7
+ return f"({self.latitude}, {self.longitude})"
8
+
9
+ def __repr__(self):
10
+ return self.__str__()
@@ -0,0 +1,19 @@
1
+ import os
2
+ import sys
3
+ from datetime import datetime, timezone
4
+
5
+ import humanize
6
+
7
+ def print_info():
8
+ python_ver = sys.version.replace('\n', ' ')
9
+ print()
10
+ print(f"Build version \t: {os.getenv('RR_BUILD_VERSION', 'undefined')}")
11
+ print(f"Build time UTC \t: {os.getenv('RR_BUILD_TIME', 'undefined')}")
12
+ print(f"Current time UTC \t: {datetime.now(timezone.utc)}")
13
+ if os.getenv('RR_BUILD_TIME') is not None:
14
+ build_old = humanize.naturaltime(datetime.now(timezone.utc) - datetime.fromisoformat(os.getenv('RR_BUILD_TIME')))
15
+ print(f"Build old\t\t: {build_old}")
16
+ print(f"PWD \t: {os.getcwd()}")
17
+ print(f"Python \t: {python_ver}")
18
+ print("---")
19
+ print()
@@ -0,0 +1,22 @@
1
+ class RedisSingletonLock:
2
+ def __init__(self, redis, lock_key=None, lock_timeout=30):
3
+ self.redis = redis
4
+ self.lock_key = lock_key
5
+ self.lock_timeout = lock_timeout
6
+ self.lock_acquired = False
7
+
8
+ def acquire_lock(self):
9
+ is_locked = self.redis.set(self.lock_key, "LOCKED", nx=True, ex=self.lock_timeout)
10
+ if is_locked:
11
+ self.lock_acquired = True
12
+ return
13
+ raise RuntimeError("Another instance is already running.")
14
+
15
+ def refresh_lock(self):
16
+ if self.lock_acquired:
17
+ self.redis.expire(self.lock_key, self.lock_timeout)
18
+
19
+ def release_lock(self):
20
+ if self.lock_acquired:
21
+ self.redis.delete(self.lock_key)
22
+ self.lock_acquired = False
@@ -0,0 +1,32 @@
1
+ import sys
2
+ import threading
3
+ import time
4
+ import traceback
5
+
6
+ import requests
7
+
8
+ _local_sessions = threading.local()
9
+
10
+
11
+ def get_session_data():
12
+ if not hasattr(_local_sessions, "session"):
13
+ _local_sessions.session = (requests.Session(), 0)
14
+
15
+ session, counter = _local_sessions.session
16
+ counter += 1
17
+ _local_sessions.session = (session, counter)
18
+
19
+ return session, counter
20
+
21
+
22
+ def make_request_wrapper(request_cb=None, sleep_times=(1, 5, 10, 15, 20, 25, 30, 30, None), **all_params):
23
+ for sleep_time in sleep_times:
24
+ try:
25
+ return request_cb(**all_params)
26
+ except Exception as e:
27
+ print(f"Error [{repr(e)}] and sleep for {sleep_time}", file=sys.stderr)
28
+ traceback.print_exc()
29
+ if sleep_time is None:
30
+ raise e
31
+ time.sleep(sleep_time)
32
+ raise Exception("Unknown error")
@@ -0,0 +1,30 @@
1
+ import signal
2
+ import threading
3
+
4
+
5
+ class SignalHandler:
6
+ _instance = None
7
+
8
+ def __init__(self, use_exception=False):
9
+ if self._instance is not None:
10
+ raise Exception("This class is a singleton!")
11
+
12
+ SignalHandler._instance = self
13
+
14
+ self.stop_event = threading.Event()
15
+
16
+ signal.signal(signal.SIGINT, self.exit_gracefully)
17
+ signal.signal(signal.SIGTERM, self.exit_gracefully)
18
+
19
+ @classmethod
20
+ def get(cls):
21
+ if cls._instance is None:
22
+ cls()
23
+ return cls._instance
24
+
25
+ def exit_gracefully(self, *args):
26
+ print("SIGNAL STOP")
27
+ self.stop_event.set()
28
+
29
+ def is_exit_app(self):
30
+ return self.stop_event.is_set()
@@ -0,0 +1,39 @@
1
+ import time
2
+
3
+
4
+ class StopWatch:
5
+ def __init__(self):
6
+ self._start_time = time.time()
7
+ self._last_stop_time = self._start_time
8
+ self._named_periods = {}
9
+ self.saved = None
10
+
11
+ def __enter__(self):
12
+ return self
13
+
14
+ def __exit__(self, type, value, traceback):
15
+ self.stop()
16
+
17
+ def __repr__(self):
18
+ return f"{self.saved:>2.1f}"
19
+
20
+ def store(self, name):
21
+ _time = time.time()
22
+ self._named_periods[name] = _time - self._last_stop_time
23
+ self._last_stop_time = _time
24
+
25
+ def get_time(self, name):
26
+ return self._named_periods[name]
27
+
28
+ def get_until_now(self):
29
+ return time.time() - self._start_time
30
+
31
+ def is_more_than_restart(self, time_limit_sec):
32
+ _delta = time.time() - self._start_time
33
+ if _delta < time_limit_sec:
34
+ return False
35
+ self._start_time = time.time()
36
+ return True
37
+
38
+ def stop(self):
39
+ self.saved = time.time() - self._start_time