common-util-py 0.0.23__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.
cli/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ cli module
4
+ """
5
+
6
+ import subprocess
7
+ from . import timeout
8
+
9
+
10
+ def run(command):
11
+ """
12
+ Run a command and return the output and error.
13
+ """
14
+ # bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
15
+ with subprocess.Popen(command.split(), stdout=subprocess.PIPE) as process:
16
+ output, error = process.communicate()
17
+ return (output, error)
18
+
19
+
20
+ __all__ = [
21
+ "timeout",
22
+ ]
cli/test_timeout.py ADDED
@@ -0,0 +1,98 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Unit tests for timeout.py
4
+ """
5
+
6
+ from unittest import mock
7
+ import sys
8
+ import subprocess
9
+ import signal
10
+
11
+ import pytest
12
+
13
+ from cli import timeout
14
+
15
+
16
+ def test_timeout_exception():
17
+ """Test that TimeoutException is raised by the handler."""
18
+ with pytest.raises(timeout.TimeoutException):
19
+ timeout.timeout_handler(signal.SIGALRM, None)
20
+
21
+
22
+ def test_cuda_exception():
23
+ """Test CUDAException can be raised and caught."""
24
+ with pytest.raises(timeout.CUDAException):
25
+ raise timeout.CUDAException("CUDA error detected")
26
+
27
+
28
+ def test_env_timeout(monkeypatch):
29
+ """Test TIMEOUT_NO_ACTIVITY_SECONDS env var parsing."""
30
+ monkeypatch.setenv("TIMEOUT_NO_ACTIVITY_SECONDS", "123")
31
+ import importlib
32
+ from cli import timeout as t_reload
33
+
34
+ importlib.reload(t_reload)
35
+ assert t_reload.TIMEOUT_NO_ACTIVITY_SECONDS == 123
36
+
37
+
38
+ def test_execute_keyboard_interrupt(monkeypatch):
39
+ """Test execute handles KeyboardInterrupt and exits loop."""
40
+
41
+ class DummyProc:
42
+ """Patch subprocess.Popen to simulate a process"""
43
+
44
+ def __init__(self):
45
+ self.stdout = mock.Mock()
46
+ self.stdout.readline = mock.Mock(side_effect=KeyboardInterrupt)
47
+
48
+ def __enter__(self):
49
+ return self
50
+
51
+ def __exit__(self, exc_type, exc_val, exc_tb):
52
+ return False
53
+
54
+ def send_signal(self, sig):
55
+ """Send signal to process"""
56
+
57
+ def wait(self, timeout=None):
58
+ """Wait for process to finish"""
59
+
60
+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: DummyProc())
61
+ # Patch signal.signal and signal.alarm to do nothing
62
+ monkeypatch.setattr(signal, "signal", lambda *a, **k: None)
63
+ monkeypatch.setattr(signal, "alarm", lambda *a, **k: None)
64
+ # Should exit cleanly
65
+ timeout.execute([sys.executable, "-c", "print('ok')"])
66
+
67
+
68
+ '''
69
+ def test_execute_timeout(monkeypatch):
70
+ """Test execute handles TimeoutException and restarts once."""
71
+ class DummyProc:
72
+ def __init__(self):
73
+ self.stdout = mock.Mock()
74
+ self.stdout.readline = mock.Mock(side_effect=["line", "", TimeoutError])
75
+ def __enter__(self): return self
76
+ def __exit__(self, exc_type, exc_val, exc_tb): return False
77
+ def send_signal(self, sig): pass
78
+ def wait(self, timeout=None): pass
79
+
80
+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: DummyProc())
81
+ monkeypatch.setattr(signal, "signal", lambda *a, **k: None)
82
+ monkeypatch.setattr(signal, "alarm", lambda *a, **k: None)
83
+
84
+ # Add a counter to break the loop after one restart
85
+ call_count = {"count": 0}
86
+ orig_execute = timeout.execute
87
+
88
+ def limited_execute(cmd):
89
+ if call_count["count"] > 0:
90
+ return # Exit after first restart
91
+ call_count["count"] += 1
92
+ return orig_execute(cmd)
93
+
94
+ with mock.patch("cli.timeout.logging") as mock_log:
95
+ monkeypatch.setattr(timeout, "execute", limited_execute)
96
+ timeout.execute([sys.executable, "-c", "print('ok')"])
97
+ assert mock_log.error.called
98
+ '''
cli/timeout.py ADDED
@@ -0,0 +1,82 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Timeout script for CUDA applications
4
+
5
+ Only work for linux since it use singal.SIGALRM
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import signal
11
+ import subprocess
12
+ import sys
13
+
14
+
15
+ logging.basicConfig(
16
+ level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s"
17
+ )
18
+
19
+ try:
20
+ TIMEOUT_NO_ACTIVITY_SECONDS = int(os.getenv("TIMEOUT_NO_ACTIVITY_SECONDS", "60"))
21
+ except (ValueError, TypeError):
22
+ TIMEOUT_NO_ACTIVITY_SECONDS = 60
23
+
24
+
25
+ class CUDAException(Exception):
26
+ """CUDA error exception"""
27
+
28
+
29
+ class TimeoutException(Exception):
30
+ """Time out exception"""
31
+
32
+
33
+ def timeout_handler(signum, frame):
34
+ """Timeout handler"""
35
+ raise TimeoutException(
36
+ f"No activity from app for {TIMEOUT_NO_ACTIVITY_SECONDS} seconds"
37
+ )
38
+
39
+
40
+ def execute(cmd):
41
+ """
42
+ Execute a command, restarting on CUDA errors or inactivity.
43
+ Args:
44
+ cmd (list): The command and arguments to run as a subprocess.
45
+ """
46
+ signal.signal(signal.SIGALRM, timeout_handler)
47
+
48
+ shutdown = False
49
+ while not shutdown:
50
+ with subprocess.Popen(
51
+ cmd,
52
+ bufsize=0, # unbuffered so immediately print out
53
+ stdout=subprocess.PIPE,
54
+ stderr=subprocess.STDOUT,
55
+ universal_newlines=True,
56
+ ) as proc:
57
+ try:
58
+ signal.alarm(TIMEOUT_NO_ACTIVITY_SECONDS)
59
+ for line in iter(proc.stdout.readline, ""):
60
+ line = line.strip()
61
+ logging.info(line)
62
+ if line.startswith("CUDA error"):
63
+ raise CUDAException("****** Restarting due to CUDA error")
64
+ signal.alarm(TIMEOUT_NO_ACTIVITY_SECONDS)
65
+ except (CUDAException, TimeoutException) as e:
66
+ logging.error(str(e))
67
+ except KeyboardInterrupt:
68
+ shutdown = True
69
+
70
+ signal.alarm(0)
71
+
72
+ proc.send_signal(signal.SIGINT)
73
+
74
+ try:
75
+ proc.wait(timeout=15)
76
+ except subprocess.TimeoutExpired:
77
+ logging.error("app didn't shutdown within 5 seconds")
78
+ proc.kill()
79
+
80
+
81
+ if __name__ == "__main__":
82
+ execute(sys.argv[1:])
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: common_util_py
3
+ Version: 0.0.23
4
+ Summary: Common Python utility modules
5
+ Home-page: https://github.com/jasonwee/common-util-py
6
+ Author: Jason Wee
7
+ Author-email: Jason Wee <peichieh@gmail.com>
8
+ Maintainer-email: Jason Wee <peichieh@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ Project-URL: Homepage, https://github.com/jasonwee/common-util-py
11
+ Project-URL: Documentation, https://jasonwee.github.io/common-util-py/
12
+ Project-URL: Source, https://github.com/jasonwee/common-util-py
13
+ Project-URL: Tracker, https://github.com/jasonwee/common-util-py/issues
14
+ Keywords: utilities,common,python,sql,weetech
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Programming Language :: Python :: 3
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: PyMySQL>=1.1.1
22
+ Requires-Dist: matrix-nio>=0.20.0
23
+ Requires-Dist: SQLAlchemy>=2.0.41
24
+ Requires-Dist: mysql-connector-python>=9.4.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.4.1; extra == "dev"
27
+ Requires-Dist: twine>=6.1.0; extra == "dev"
28
+ Requires-Dist: ruff>=0.12.7; extra == "dev"
29
+ Requires-Dist: mypy>=1.17.1; extra == "dev"
30
+ Requires-Dist: build>=1.3.0; extra == "dev"
31
+ Dynamic: author
32
+ Dynamic: home-page
33
+ Dynamic: license-file
34
+
35
+ ## common-util-py
36
+ Common utilities in Python
37
+
38
+ ## How to install
39
+ The following commands show how to install `common-util-py` using pip within a Python virtual environment. To see which versions of Python are supported by `common-util-py`, see (here)[#tested-installation-via-pypi-on-the-following-python-versions].
40
+ ```sh
41
+ $ python3 -m venv py313_env
42
+ $ source py313_env/bin/activate
43
+ $ pip install .[dev]
44
+ $ # or
45
+ $ virtualenv --python=/usr/bin/python3 py39_env
46
+ $ source env_py39/bin/activate
47
+ $ pip install .
48
+ $ # or
49
+ $ python3.8 -m venv env_py38
50
+ $ source env_py38/bin/activate
51
+ $ pip install .
52
+ ```
53
+
54
+ ## How to build
55
+ To create a source distribution, run the following commands:
56
+ ```sh
57
+ $ source py313_env/bin/activate
58
+ $ python3 setup.py --help-commands
59
+ $ python3 setup.py sdist
60
+ ```
61
+
62
+ ## How to test
63
+ Initially we were using `nosetests` and have since migrated to `pytest`.
64
+ ```sh
65
+ $ # deprecated
66
+ $ # python setup.py test
67
+ $ # python setup.py nosetests
68
+ $ # nose is replace by pytest since python3.13
69
+ $ pytest
70
+ ```
71
+
72
+ read more [here](https://nose.readthedocs.io/en/latest/setuptools_integration.html)
73
+
74
+
75
+ * https://www.codingforentrepreneurs.com/blog/pipenv-virtual-environments-for-python/
76
+ * https://packaging.python.org/
77
+ * https://betterscientificsoftware.github.io/python-for-hpc/tutorials/python-pypi-packaging/
78
+
79
+ ## How to upload to PyPI (Python Package Index)
80
+ First, build a source distribution and then install the `twine` package.
81
+ ```sh
82
+ $ python setup.py sdist
83
+ $ pip install twine
84
+ ```
85
+ Then, use twine to upload the package to PyPI.
86
+ ```sh
87
+ $ twine upload --repository-url https://test.pypi.org/legacy/ dist/*
88
+ ```
89
+ or
90
+ ```sh
91
+ $ twine upload --config-file ~/.pypirc -r testpypi dist/common_util_py-0.0.1.tar.gz
92
+ ```
93
+
94
+ ## Test install
95
+ Install from Test PyPI
96
+ ```sh
97
+ $ pip install --index-url https://test.pypi.org/simple/ common-util-py
98
+ ```
99
+ Install from Local Distribution.
100
+ ```sh
101
+ $ pip install dist/common_util_py-<version>.tar.gz
102
+ ```
103
+
104
+ ## Legacy
105
+ To generate `requirements.txt` and `requirements-dev.txt` from `pyproject.toml`, run the following command.
106
+ ```
107
+ pip install pip-tools
108
+ pip-compile --extra dev pyproject.toml -o requirements-dev.txt
109
+ pip-compile pyproject.toml -o requirements.txt
110
+ ```
111
+
112
+ ## Tested installation via PyPI on the following Python versions:
113
+ | Python Version | tested installed |
114
+ | --------------- |:-----------------:|
115
+ | 3.9 | Yes |
116
+ | 3.10 | Yes |
117
+ | 3.11 | Yes |
118
+ | 3.12 | Yes |
119
+ | 3.13 | Yes |
120
+ | 3.14 | Upcoming |
121
+
122
+
@@ -0,0 +1,40 @@
1
+ cli/__init__.py,sha256=mJdF-4PJ3gauSin8ApdXNp26TuqLxMKJWkgDL2_FV0Y,416
2
+ cli/test_timeout.py,sha256=5gXZjmNzLPN0YakqDyY5nd5H7dEO9aGWyBD_oA4tG0E,3052
3
+ cli/timeout.py,sha256=nrTkP19FmXqP7d6TxJ5HDlUBuyIA65ri94s1b4U86Mk,2147
4
+ common_util_py-0.0.23.dist-info/licenses/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
5
+ db/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ db/mysql.py,sha256=0qt5B_HGBZJPF5tORb2MT8YqdaWkpee3xt9C0vc4XBc,2765
7
+ db/sql.py,sha256=RLMywkKp7I6s6f1xWGg0p0rVA8fWozy_cxSny7VRkdQ,2182
8
+ fastapi/BackgroundTasks/client2.py,sha256=hnjrnFmVQWuJ6HdJH18rfddte1O3nUvEu7a7CNGuv9U,233
9
+ fastapi/BackgroundTasks/main.py,sha256=NKN8UkjKl36KEJ8DgluqZN97JiTELvpHShPEtCaaGm4,425
10
+ fastapi/BackgroundTasks/main1.py,sha256=uoiAGVcRopO-2-BOFMnXIqG1iB-8PG2GJWVHNODpTvU,872
11
+ fastapi/BackgroundTasks/main2.py,sha256=_2GacHnDCJEMLKS6YL06O9hVe1xhObeeP62p2JJzFK8,1033
12
+ fastapi/BackgroundTasks_middleware/main.py,sha256=pY21sdvZCLAmb8IcWop15jQ3OmzuNLnGz1eYcs2b9AU,758
13
+ fastapi/middleware/main.py,sha256=V3KPGgkx298W4ZH_gvWnA-BijTkkXes6PDFYSSEvLec,430
14
+ files/__init__.py,sha256=OAbkL4M6JDke2ujbZHAAex5h0s0k7UdSo7aT-lMLh0g,893
15
+ files/json_file.py,sha256=ruwd6-7iS0ZchLUO1cSVPi8BjwB1eWJqN0CPuPmuSmM,2082
16
+ files/test_files.py,sha256=ewrQUX7_7uGJ3zLkN9cQD2053jpw8QxkPcj148uiuJk,1681
17
+ files/test_json_file.py,sha256=ucVdfBWhHlt9zNYh4dcyBpUmFrG3SKzKnRHfEOguU_k,3508
18
+ httpclient/__init__.py,sha256=r8pQvFdTGhWdS0VIrVKXk1sLbd2mFT8WD4RkuUgBKGE,301
19
+ httpclient/test_httpclient.py,sha256=dLRAGha1RVpwV5VbEIWugTx-_luTrxRq0PZIJc8ftoM,1157
20
+ httpclient/get/sample.py,sha256=v0nJ1hEGDBdlPGCqrZ7dJdqBen00q3Utrde0FjIgr_A,2687
21
+ ip/__init__.py,sha256=2B6ToWPs593njpJTN5n7jzNOExdwciR1u3nCZ3Mzifg,128
22
+ ip/hostname.py,sha256=leebDReN8WVaZbpneRrBSxaIO9_pbvcVKnx1Mo8oxH0,338
23
+ ip/ipv4.py,sha256=2Y_zdAjHT7vWyqSy3FUFWnX33gT58mvtLsX8MFnJl4I,124
24
+ ip/ipv6.py,sha256=KOlZi3_JRzmkSEWqjzTDjgXkKJm99iqtCYIKVx8sVdo,141
25
+ logger/__init__.py,sha256=D5WV7VuN2p5MRFfk7weoz1zA67lQLcPu0tZt6fTzxpM,21
26
+ logger/log.py,sha256=H0zcjFj_M5Ic0_lCILmTOv9ZWYp9GJglMk0WNaP9V6w,124
27
+ mailer/__init__.py,sha256=oUg_X7U9m90TFAHoz2gTdeIb1KTWeecaHN3vZ4dxjTg,245
28
+ mailer/email.py,sha256=qP8maqksmD3GTTqgLF-EgBM7uyZ4WUbhkSEvb65us08,125
29
+ mailer/gmail.py,sha256=RfJevrXZVlJEWYB9ti7jowQVsC5aPvVTleFDwsuMNS4,119
30
+ mailer/mailer.py,sha256=6An48dE2ZCUh-mcLoiuxBzhgtlBCromDJD2IbzwhdkU,3172
31
+ mailer/test_email_address.py,sha256=JmW6xe3AwMxS81acXIMFe9sQRrw6-vKa90D9El4sh9Y,2640
32
+ maths/__init__.py,sha256=EAY_KunuK4gm3BoFWvTuabGglJ32KSpGEtoxmWNge1Y,83
33
+ matrixclient/__init__.py,sha256=j3bhYSB4GZWKG0kQUg56lGdiamppiDgCJKcjzjIRU6c,718
34
+ matrixclient/htmlmsg.py,sha256=xyKTwkPTUxS3zW7uIj208D03PHvNBr5KYv4uEfYkhkw,2915
35
+ matrixclient/matrixclient.py,sha256=JeeXIc6agxmvVRtn86Gdi8kWfMNrRGXMs67vorN-ngM,12106
36
+ wt_datetime/__init__.py,sha256=sOvcKaYy5kr12K3jkzqEURuv1MZauy6mxofkp1a2Mkg,161
37
+ common_util_py-0.0.23.dist-info/METADATA,sha256=XzlmvMn8I9rzgvKswK4Mc-tHnyMaoL_zp6RxpdrEYS4,3864
38
+ common_util_py-0.0.23.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
39
+ common_util_py-0.0.23.dist-info/top_level.txt,sha256=BYe73Xz5srTYKSfq6Dw7gbQM6CmWfccLpa8yyo-IoGU,80
40
+ common_util_py-0.0.23.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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,11 @@
1
+ cli
2
+ db
3
+ fastapi
4
+ files
5
+ httpclient
6
+ ip
7
+ logger
8
+ mailer
9
+ maths
10
+ matrixclient
11
+ wt_datetime
db/__init__.py ADDED
File without changes
db/mysql.py ADDED
@@ -0,0 +1,79 @@
1
+ import mysql.connector
2
+
3
+ # pip install mysql-connector-python
4
+ # https://www.w3schools.com/python/python_mysql_getstarted.asp
5
+ class Mysql:
6
+
7
+ def __init__(self, host, username, password):
8
+ self.host = host
9
+ self.username = username
10
+ self.password = password
11
+
12
+ self.mydb = mysql.connector.connect(
13
+ host = self.host,
14
+ user = self.username,
15
+ password = self.password
16
+ )
17
+
18
+ # create
19
+ def create(self, statement, vals=()):
20
+ # create database mydb
21
+ # show databases
22
+ # CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))
23
+ #"INSERT INTO customers (name, address) VALUES (%s, %s)" | ("John", "Highway 21")
24
+ # "DROP TABLE customers"
25
+ # "DROP TABLE IF EXISTS customers"
26
+ cursor = self.mydb.cursor()
27
+ if vals:
28
+ cursor.execute(statement, vals)
29
+ self.mydb.commit()
30
+ return cursor.rowcount
31
+ else:
32
+ cursor.execute(statement)
33
+
34
+ # read
35
+ def read(self, statement, vals=()):
36
+ # SELECT * FROM customers
37
+ # SELECT name, address FROM customers
38
+ # SELECT * FROM customers WHERE address ='Park Lane 38'
39
+ # SELECT * FROM customers WHERE address = %s | ("Yellow Garden 2", )
40
+ # SELECT * FROM customers ORDER BY name
41
+ # SELECT * FROM customers ORDER BY name DESC
42
+ # SELECT * FROM customers LIMIT 5
43
+ # SELECT * FROM customers LIMIT 5 OFFSET 2
44
+ # "SELECT users.name AS user, products.name AS favorite FROM users INNER JOIN products ON users.fav = products.id
45
+ cursor = self.mydb.cursor()
46
+ if vals:
47
+ cursor.execute(statement, vals)
48
+ else:
49
+ cursor.execute(statement)
50
+ results = cursor.fetchall()
51
+ return results
52
+
53
+ # update
54
+ def update(self, statement, vals=()):
55
+ # "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
56
+ # "UPDATE customers SET address = %s WHERE address = %s" | ("Valley 345", "Canyon 123")
57
+ cursor = self.mydb.cursor()
58
+ if vals:
59
+ cursor.execute(statement, val)
60
+ else:
61
+ cursor.execute(statement)
62
+ self.mydb.commit()
63
+ return cursor.rowcount
64
+
65
+ # delete
66
+ def delete(self, statement, vals=()):
67
+ # DELETE FROM customers WHERE address = 'Mountain 21'
68
+ # DELETE FROM customers WHERE address = %s | ("Yellow Garden 2", )
69
+ cursor = self.mydb.cursor()
70
+ if vals:
71
+ cursor.execute(statement, vals)
72
+ else:
73
+ cursor.execute(statement)
74
+ self.mydb.commit()
75
+ return cursor.rowcount
76
+
77
+ # general method, just return cursor, let caller do it.
78
+ def get_cursor(self):
79
+ return self.mydb.cursor()