python-plugins 0.1.7__tar.gz → 0.2.0__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 (89) hide show
  1. {python_plugins-0.1.7 → python_plugins-0.2.0}/CHANGES.rst +23 -0
  2. {python_plugins-0.1.7 → python_plugins-0.2.0}/LICENSE.rst +1 -1
  3. {python_plugins-0.1.7 → python_plugins-0.2.0}/PKG-INFO +5 -4
  4. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/usage.rst +8 -3
  5. {python_plugins-0.1.7 → python_plugins-0.2.0}/pyproject.toml +2 -1
  6. {python_plugins-0.1.7 → python_plugins-0.2.0}/requirements/test.in +2 -1
  7. python_plugins-0.2.0/src/python_plugins/__about__.py +1 -0
  8. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/convert/__init__.py +1 -0
  9. python_plugins-0.2.0/src/python_plugins/crypto/__init__.py +2 -0
  10. python_plugins-0.2.0/src/python_plugins/crypto/file_to_file.py +70 -0
  11. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/crypto/str_to_list.py +11 -16
  12. python_plugins-0.2.0/src/python_plugins/examples/higher_order_functions.py +40 -0
  13. python_plugins-0.2.0/src/python_plugins/forms/fields/__init__.py +2 -0
  14. python_plugins-0.2.0/src/python_plugins/forms/fields/datetime.py +100 -0
  15. python_plugins-0.2.0/src/python_plugins/forms/fields/json.py +19 -0
  16. python_plugins-0.2.0/src/python_plugins/forms/fields/select.py +123 -0
  17. python_plugins-0.2.0/src/python_plugins/forms/fields/switch.py +10 -0
  18. python_plugins-0.2.0/src/python_plugins/forms/fields/taglist.py +9 -0
  19. python_plugins-0.2.0/src/python_plugins/forms/mixins/__init__.py +0 -0
  20. python_plugins-0.2.0/src/python_plugins/forms/mixins/user.py +29 -0
  21. python_plugins-0.2.0/src/python_plugins/forms/widgets/__init__.py +0 -0
  22. python_plugins-0.2.0/src/python_plugins/forms/widgets/datetime.py +30 -0
  23. python_plugins-0.2.0/src/python_plugins/forms/widgets/file.py +4 -0
  24. python_plugins-0.2.0/src/python_plugins/forms/widgets/select.py +26 -0
  25. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/jwt/jwt.py +0 -9
  26. python_plugins-0.2.0/src/python_plugins/models/__init__.py +0 -0
  27. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/token_minxin.py +4 -1
  28. python_plugins-0.2.0/src/python_plugins/utils/__init__.py +1 -0
  29. python_plugins-0.2.0/tests/__init__.py +1 -0
  30. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_crypt_file.py +23 -21
  31. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_crypto.py +1 -20
  32. python_plugins-0.2.0/tests/test_forms.py +65 -0
  33. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_utils.py +2 -2
  34. python_plugins-0.1.7/src/python_plugins/__about__.py +0 -1
  35. python_plugins-0.1.7/src/python_plugins/__init__.py +0 -1
  36. python_plugins-0.1.7/src/python_plugins/crypto/__init__.py +0 -1
  37. python_plugins-0.1.7/src/python_plugins/crypto/file_to_file.py +0 -112
  38. {python_plugins-0.1.7 → python_plugins-0.2.0}/.github/workflows/release.yml +0 -0
  39. {python_plugins-0.1.7 → python_plugins-0.2.0}/.gitignore +0 -0
  40. {python_plugins-0.1.7 → python_plugins-0.2.0}/.readthedocs.yaml +0 -0
  41. {python_plugins-0.1.7 → python_plugins-0.2.0}/README.rst +0 -0
  42. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/Makefile +0 -0
  43. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/api.rst +0 -0
  44. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/changes.rst +0 -0
  45. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/conf.py +0 -0
  46. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/examples.rst +0 -0
  47. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/index.rst +0 -0
  48. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/make.bat +0 -0
  49. {python_plugins-0.1.7 → python_plugins-0.2.0}/docs/requirements.txt +0 -0
  50. {python_plugins-0.1.7 → python_plugins-0.2.0}/examples/README.rst +0 -0
  51. {python_plugins-0.1.7 → python_plugins-0.2.0}/requirements/build.in +0 -0
  52. {python_plugins-0.1.7/tests → python_plugins-0.2.0/src/python_plugins}/__init__.py +0 -0
  53. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/convert/datetime_str.py +0 -0
  54. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/convert/pretty.py +0 -0
  55. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/convert/xml.py +0 -0
  56. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/crypto/fernet.py +0 -0
  57. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/dumps/__init__.py +0 -0
  58. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/dumps/postgresql_dump.py +0 -0
  59. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/email/__init__.py +0 -0
  60. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/email/smtp.py +0 -0
  61. {python_plugins-0.1.7/src/python_plugins/models → python_plugins-0.2.0/src/python_plugins/forms}/__init__.py +0 -0
  62. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/hashes/__init__.py +0 -0
  63. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/hashes/hash.py +0 -0
  64. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/jwt/__init__.py +0 -0
  65. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/__init__.py +0 -0
  66. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/data_mixin.py +0 -0
  67. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/primary_key_mixin.py +0 -0
  68. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/timestamp_mixin.py +0 -0
  69. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/mixins/user_minxin.py +0 -0
  70. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/models/update.py +0 -0
  71. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/process/__init__.py +0 -0
  72. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/process/python_venv_process.py +0 -0
  73. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/process/sub_process.py +0 -0
  74. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/random/__init__.py +0 -0
  75. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/random/random_str.py +0 -0
  76. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/utils/remove_pycache.py +0 -0
  77. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/biz_data_crypt.py +0 -0
  78. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/error_code.py +0 -0
  79. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/format_response.py +0 -0
  80. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/wechat.py +0 -0
  81. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/wechat_crypt.py +0 -0
  82. {python_plugins-0.1.7 → python_plugins-0.2.0}/src/python_plugins/weixin/weixin_api.py +0 -0
  83. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/conftest.py +0 -0
  84. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_email.py +0 -0
  85. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_jwt.py +0 -0
  86. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_process.py +0 -0
  87. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_random.py +0 -0
  88. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_sqlalchemy.py +0 -0
  89. {python_plugins-0.1.7 → python_plugins-0.2.0}/tests/test_weixin.py +0 -0
@@ -1,3 +1,26 @@
1
+ v0.2.0
2
+ ------
3
+
4
+ Released 2024-11-20
5
+
6
+ - add forms
7
+
8
+
9
+ v0.1.9
10
+ ------
11
+
12
+ Released 2024-11-19
13
+
14
+ - add forms
15
+
16
+
17
+ v0.1.8
18
+ ------
19
+
20
+ Released 2024-11-19
21
+
22
+ - add examples for learning
23
+
1
24
  v0.1.7
2
25
  ------
3
26
 
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024-present huadong <david.dong.hua@gmail.com>
3
+ Copyright (c) 2024-present DavidDongHua <david.dong.hua@gmail.com>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: python-plugins
3
- Version: 0.1.7
3
+ Version: 0.2.0
4
4
  Summary: A collection of Python functions and classes.
5
5
  Project-URL: Documentation, https://python-plugins.readthedocs.io
6
6
  Project-URL: Source, https://github.com/ojso/python-plugins
7
7
  Project-URL: Homepage, https://github.com/ojso/python-plugins
8
- Author-email: huadong <david.dong.hua@gmail.com>
8
+ Author-email: David Hua <david.dong.hua@gmail.com>
9
9
  License: MIT License
10
10
 
11
- Copyright (c) 2024-present huadong <david.dong.hua@gmail.com>
11
+ Copyright (c) 2024-present DavidDongHua <david.dong.hua@gmail.com>
12
12
 
13
13
  Permission is hereby granted, free of charge, to any person obtaining a copy
14
14
  of this software and associated documentation files (the "Software"), to deal
@@ -27,7 +27,6 @@ License: MIT License
27
27
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
28
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
29
  SOFTWARE.
30
- License-File: LICENSE.rst
31
30
  Keywords: plugin,utils
32
31
  Classifier: Development Status :: 3 - Alpha
33
32
  Classifier: Intended Audience :: Developers
@@ -50,6 +49,8 @@ Provides-Extra: requests
50
49
  Requires-Dist: requests; extra == 'requests'
51
50
  Provides-Extra: sqlalchemy
52
51
  Requires-Dist: sqlalchemy; extra == 'sqlalchemy'
52
+ Provides-Extra: wtforms
53
+ Requires-Dist: wtforms; extra == 'wtforms'
53
54
  Description-Content-Type: text/x-rst
54
55
 
55
56
  python-plugins
@@ -42,14 +42,19 @@ mixins
42
42
  .. code-block:: python
43
43
 
44
44
  from flask_sqlalchemy import SQLAlchemy
45
+ from sqlalchemy.orm import DeclarativeBase
46
+
45
47
  from python_plugins.models.mixins import PrimaryKeyMixin
46
48
  from python_plugins.models.mixins import UserMixin
47
49
  from python_plugins.models.mixins import DataMixin
48
50
  from python_plugins.models.mixins import TimestampMixin
49
51
 
50
- db = SQLAlchemy()
52
+ class Base(DeclarativeBase):
53
+ pass
54
+
55
+ db = SQLAlchemy(model_class=Base)
51
56
 
52
- class User(PrimaryKeyMixin, DataMixin, TimestampMixin, UserMixin, db.models):
57
+ class User(db.models,PrimaryKeyMixin, DataMixin, TimestampMixin, UserMixin):
53
58
  __tablename__ = "users"
54
59
 
55
60
  remove_pycache
@@ -57,7 +62,7 @@ remove_pycache
57
62
 
58
63
  .. code-block:: python
59
64
 
60
- from python_plugins.utils.remove_pycache import remove_pycache
65
+ from python_plugins.utils import remove_pycache
61
66
 
62
67
  remove_pycache() # default is "."
63
68
  remove_pycache("./tests")
@@ -10,7 +10,7 @@ readme = "README.rst"
10
10
  license = { file = "LICENSE.rst" }
11
11
  keywords = ["plugin", "utils"]
12
12
  authors = [
13
- { name = "huadong", email = "david.dong.hua@gmail.com" },
13
+ { name = "David Hua", email = "david.dong.hua@gmail.com" },
14
14
  ]
15
15
  classifiers = [
16
16
  "Development Status :: 3 - Alpha",
@@ -30,6 +30,7 @@ dependencies = [
30
30
  cryptography = ["cryptography"]
31
31
  requests = ["requests"]
32
32
  sqlalchemy = ["SQLAlchemy"]
33
+ wtforms = ["WTForms"]
33
34
  pillow = ["pillow"]
34
35
  qrcode = ["qrcode"]
35
36
  jwt = ["PyJWT"]
@@ -3,4 +3,5 @@ Faker
3
3
  cryptography
4
4
  SQLAlchemy
5
5
  PyJWT
6
- requests
6
+ requests
7
+ WTForms
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -1,2 +1,3 @@
1
1
  from .datetime_str import datetime2str, str2datetime
2
2
  from .xml import xml2dict
3
+ from .pretty import prettify_class_name
@@ -0,0 +1,2 @@
1
+ from .fernet import generate_fernet_key, fernet_encrypt, fernet_decrypt
2
+ from .file_to_file import encrypt_txtfile, decrypt_txtfile
@@ -0,0 +1,70 @@
1
+ import re
2
+ from getpass import getpass
3
+ from .str_to_list import encrypt_str_to_list
4
+ from .str_to_list import decrypt_list_to_str
5
+
6
+ def get_prompts_line(s, pattern=r"prompts\((\d+)\)"):
7
+ match = re.search(pattern, s)
8
+ if match:
9
+ return int(match[1])
10
+
11
+ def str_from_txtfile(fin) -> str:
12
+ with open(fin, encoding="utf-8") as f:
13
+ s = f.read()
14
+ return s
15
+
16
+
17
+ def str_to_txtfile(s: str, fout=None):
18
+ if fout is None:
19
+ print(s)
20
+ else:
21
+ with open(fout, "w", encoding="utf-8") as f:
22
+ f.write(s)
23
+
24
+ def encrypt_txtfile(fin, fout=None, password=None, prompt='prompts(1)'):
25
+ s = str_from_txtfile(fin)
26
+
27
+ if not prompt:
28
+ prompt = input("input prompt=")
29
+
30
+ if password == "[input]":
31
+ password = getpass("input password=")
32
+
33
+ if password:
34
+ encrypted_list = encrypt_str_to_list(s, password)
35
+ encrypted_list[0] = "-"
36
+ else:
37
+ encrypted_list = encrypt_str_to_list(s)
38
+
39
+ s2 = "\n".join([prompt] + encrypted_list)
40
+
41
+ if fout == ".":
42
+ fout = fin+"_1"
43
+
44
+ str_to_txtfile(s2, fout)
45
+
46
+
47
+ def decrypt_txtfile(fin, fout=None, password=None):
48
+ s = str_from_txtfile(fin)
49
+ if password == "[input]":
50
+ password = getpass("input password=")
51
+ s_list = s.split("\n")
52
+ prompts = get_prompts_line(s_list[0])
53
+ if prompts is None:
54
+ prompts_line = 1
55
+ else:
56
+ prompts_line = prompts
57
+ encrypted_list = s_list[prompts_line:]
58
+
59
+ if encrypted_list[0] == "-" and password is None:
60
+ password = getpass("input password=")
61
+
62
+ if password is None:
63
+ s2 = decrypt_list_to_str(encrypted_list)
64
+ else:
65
+ s2 = decrypt_list_to_str(encrypted_list, password)
66
+
67
+ if fout == ".":
68
+ fout = fin+"_2"
69
+ str_to_txtfile(s2, fout)
70
+
@@ -1,10 +1,13 @@
1
1
  import base64
2
2
  import os
3
3
  import random
4
+ import string
4
5
  from cryptography.fernet import Fernet
5
6
  from cryptography.hazmat.primitives import hashes
6
7
  from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
7
- from ..random import rand_letter
8
+
9
+ def rand_letter(n: int):
10
+ return "".join(random.choices(string.ascii_letters + string.digits, k=n))
8
11
 
9
12
 
10
13
  def bytes_to_url64str(bstr: bytes):
@@ -54,34 +57,26 @@ def str_randsplit_to_list(s, n1=10, n2=30):
54
57
  return r
55
58
 
56
59
 
57
- def encrypt_bytes_to_list(s: bytes, password=None, prefix=None):
60
+ def encrypt_bytes_to_list(s: bytes, password=None):
58
61
  if password is None:
59
62
  password = rand_letter(random.randint(6, 16))
60
- out_password = password
61
- else:
62
- out_password = "-"
63
- if prefix is not None:
64
- password = str(prefix) + password
65
-
66
63
  key, safe_salt, times = get_key(password)
67
64
 
68
65
  cipher_suite = Fernet(key)
69
66
  encrypted_data = cipher_suite.encrypt(s)
70
67
  safe_data = bytes_to_url64str(encrypted_data)
71
68
 
72
- list_out = [out_password, safe_salt, str(times)] + str_randsplit_to_list(safe_data)
69
+ list_out = [password, safe_salt, str(times)] + str_randsplit_to_list(safe_data)
73
70
 
74
71
  return list_out
75
72
 
76
73
 
77
- def decrypt_list_to_bytes(list_in, password=None, prefix=None) -> bytes:
74
+ def decrypt_list_to_bytes(list_in, password=None) -> bytes:
78
75
  _password, safe_salt, _times, *_data = list_in
79
76
  if password is None:
80
77
  password = _password
81
78
  else:
82
79
  password = password
83
- if prefix is not None:
84
- password = str(prefix) + password
85
80
 
86
81
  times = int(_times)
87
82
  s = "".join(_data)
@@ -91,11 +86,11 @@ def decrypt_list_to_bytes(list_in, password=None, prefix=None) -> bytes:
91
86
  return decrypted_bytes
92
87
 
93
88
 
94
- def encrypt_str_to_list(s: str, password=None, prefix=None):
95
- arr = encrypt_bytes_to_list(s.encode(), password, prefix)
89
+ def encrypt_str_to_list(s: str, password=None):
90
+ arr = encrypt_bytes_to_list(s.encode(), password)
96
91
  return arr
97
92
 
98
93
 
99
- def decrypt_list_to_str(list_in, password=None, prefix=None):
100
- decrypted_bytes = decrypt_list_to_bytes(list_in, password, prefix)
94
+ def decrypt_list_to_str(list_in, password=None):
95
+ decrypted_bytes = decrypt_list_to_bytes(list_in, password)
101
96
  return decrypted_bytes.decode()
@@ -0,0 +1,40 @@
1
+ import functools
2
+
3
+ # lambda parameters: expression
4
+
5
+ lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6
+
7
+ print(lst)
8
+
9
+ # map(function, iterable, *iterables) -> iterable
10
+
11
+ lst_2 = list(map(lambda i: i**2, lst))
12
+
13
+ print(lst_2)
14
+
15
+ print([i**2 for i in lst])
16
+
17
+ lst_3 = list(map(lambda x, y: x + y, lst, lst_2))
18
+
19
+ print(lst_3)
20
+
21
+ # filter(function, iterable) -> iterable
22
+
23
+ result = list(filter(lambda x: x % 2 == 0, lst))
24
+
25
+ print(result)
26
+
27
+ print([item for item in lst if item % 2 == 0])
28
+
29
+
30
+ # reduce(function, iterable[, initializer])
31
+
32
+ result = functools.reduce(lambda x, y: x + y, lst)
33
+
34
+ print(result)
35
+
36
+
37
+ # zip(*iterables)
38
+
39
+ # sorted(iterable, key=None, reverse=False)
40
+
@@ -0,0 +1,2 @@
1
+ from .json import JSONField
2
+ from .datetime import DateTimeField
@@ -0,0 +1,100 @@
1
+ import time
2
+ import datetime
3
+ import wtforms.fields
4
+ from ..widgets.datetime import DateTimePickerWidget
5
+ from ..widgets.datetime import TimePickerWidget
6
+
7
+ class DateTimeField(wtforms.fields.DateTimeField):
8
+ """
9
+ Allows modifying the datetime format of a DateTimeField using form_args.
10
+ """
11
+
12
+ widget = DateTimePickerWidget()
13
+
14
+ def __init__(self, label=None, validators=None, format=None, **kwargs):
15
+ """Constructor
16
+
17
+ :param label:
18
+ Label
19
+ :param validators:
20
+ Field validators
21
+ :param format:
22
+ Format for text to date conversion. Defaults to '%Y-%m-%d %H:%M:%S'
23
+ :param kwargs:
24
+ Any additional parameters
25
+ """
26
+ super().__init__(
27
+ label, validators, format or "%Y-%m-%d %H:%M:%S", **kwargs
28
+ )
29
+
30
+
31
+ class TimeField(wtforms.fields.Field):
32
+ """
33
+ A text field which stores a `datetime.time` object.
34
+ Accepts time string in multiple formats: 20:10, 20:10:00, 10:00 am, 9:30pm, etc.
35
+ """
36
+
37
+ widget = TimePickerWidget()
38
+
39
+ def __init__(
40
+ self,
41
+ label=None,
42
+ validators=None,
43
+ formats=None,
44
+ default_format=None,
45
+ widget_format=None,
46
+ **kwargs
47
+ ):
48
+ """
49
+ Constructor
50
+
51
+ :param label:
52
+ Label
53
+ :param validators:
54
+ Field validators
55
+ :param formats:
56
+ Supported time formats, as a enumerable.
57
+ :param default_format:
58
+ Default time format. Defaults to '%H:%M:%S'
59
+ :param kwargs:
60
+ Any additional parameters
61
+ """
62
+ super().__init__(label, validators, **kwargs)
63
+
64
+ self.formats = formats or (
65
+ "%H:%M:%S",
66
+ "%H:%M",
67
+ "%I:%M:%S%p",
68
+ "%I:%M%p",
69
+ "%I:%M:%S %p",
70
+ "%I:%M %p",
71
+ )
72
+
73
+ self.default_format = default_format or "%H:%M:%S"
74
+
75
+ def _value(self):
76
+ if self.raw_data:
77
+ return " ".join(self.raw_data)
78
+ elif self.data is not None:
79
+ return self.data.strftime(self.default_format)
80
+ else:
81
+ return ""
82
+
83
+ def process_formdata(self, valuelist):
84
+ if valuelist:
85
+ date_str = " ".join(valuelist)
86
+
87
+ if date_str.strip():
88
+ for format in self.formats:
89
+ try:
90
+ timetuple = time.strptime(date_str, format)
91
+ self.data = datetime.time(
92
+ timetuple.tm_hour, timetuple.tm_min, timetuple.tm_sec
93
+ )
94
+ return
95
+ except ValueError:
96
+ pass
97
+
98
+ raise ValueError(self.gettext("Invalid time format"))
99
+ else:
100
+ self.data = None
@@ -0,0 +1,19 @@
1
+ import json
2
+ from wtforms.fields import TextAreaField
3
+
4
+ class JSONField(TextAreaField):
5
+ def process_formdata(self, valuelist):
6
+ if valuelist:
7
+ if not valuelist[0]:
8
+ self.data = None
9
+ return
10
+ try:
11
+ self.data = json.loads(valuelist[0])
12
+ except ValueError:
13
+ raise ValueError(self.gettext("Invalid JSON"))
14
+
15
+ def _value(self):
16
+ if self.data:
17
+ return json.dumps(self.data, ensure_ascii=False)
18
+ else:
19
+ return ""
@@ -0,0 +1,123 @@
1
+ import re
2
+ import wtforms.fields
3
+ from ..widgets.select import Select2Widget
4
+ from ..widgets.select import Select2TagsWidget
5
+
6
+
7
+ class Select2Field(wtforms.fields.SelectField):
8
+ """
9
+ `Select2 <https://github.com/ivaynberg/select2>`_ styled select widget.
10
+
11
+ You must include select2.js, form-x.x.x.js and select2 stylesheet for it to
12
+ work.
13
+ """
14
+
15
+ widget = Select2Widget()
16
+
17
+ def __init__(
18
+ self,
19
+ label=None,
20
+ validators=None,
21
+ coerce=str,
22
+ choices=None,
23
+ allow_blank=False,
24
+ blank_text=None,
25
+ **kwargs
26
+ ):
27
+ super(Select2Field, self).__init__(label, validators, coerce, choices, **kwargs)
28
+ self.allow_blank = allow_blank
29
+ self.blank_text = blank_text or " "
30
+
31
+ def iter_choices(self):
32
+ if self.allow_blank:
33
+ yield ("__None", self.blank_text, self.data is None)
34
+
35
+ for choice in self.choices:
36
+ if isinstance(choice, tuple):
37
+ yield (choice[0], choice[1], self.coerce(choice[0]) == self.data)
38
+ else:
39
+ yield (
40
+ choice.value,
41
+ choice.name,
42
+ self.coerce(choice.value) == self.data,
43
+ )
44
+
45
+ def process_data(self, value):
46
+ if value is None:
47
+ self.data = None
48
+ else:
49
+ try:
50
+ self.data = self.coerce(value)
51
+ except (ValueError, TypeError):
52
+ self.data = None
53
+
54
+ def process_formdata(self, valuelist):
55
+ if valuelist:
56
+ if valuelist[0] == "__None":
57
+ self.data = None
58
+ else:
59
+ try:
60
+ self.data = self.coerce(valuelist[0])
61
+ except ValueError:
62
+ raise ValueError(self.gettext("Invalid Choice: could not coerce"))
63
+
64
+ def pre_validate(self, form):
65
+ if self.allow_blank and self.data is None:
66
+ return
67
+
68
+ super(Select2Field, self).pre_validate(form)
69
+
70
+
71
+ class Select2TagsField(wtforms.fields.StringField):
72
+ """`Select2 <http://ivaynberg.github.com/select2/#tags>`_ styled text field.
73
+ You must include select2.js, form-x.x.x.js and select2 stylesheet for it to work.
74
+ """
75
+
76
+ widget = Select2TagsWidget()
77
+ _strip_regex = re.compile(
78
+ r"#\d+(?:(,)|\s$)"
79
+ ) # e.g., 'tag#123, anothertag#425 ' => 'tag, anothertag'
80
+
81
+ def __init__(
82
+ self,
83
+ label=None,
84
+ validators=None,
85
+ save_as_list=False,
86
+ coerce=str,
87
+ allow_duplicates=False,
88
+ **kwargs
89
+ ):
90
+ """Initialization
91
+
92
+ :param save_as_list:
93
+ If `True` then populate ``obj`` using list else string
94
+ :param allow_duplicates
95
+ If `True` then duplicate tags are allowed in the field.
96
+ """
97
+ self.save_as_list = save_as_list
98
+ self.allow_duplicates = allow_duplicates
99
+ self.coerce = coerce
100
+
101
+ super(Select2TagsField, self).__init__(label, validators, **kwargs)
102
+
103
+ def process_formdata(self, valuelist):
104
+ if valuelist:
105
+ entrylist = valuelist[0]
106
+ if self.allow_duplicates and entrylist.endswith(" "):
107
+ # This means this is an allowed duplicate (see form.js, `createSearchChoice`), so its ID was modified.
108
+ # Hence, we need to restore the original IDs.
109
+ entrylist = re.sub(self._strip_regex, "\\1", entrylist)
110
+ if self.save_as_list:
111
+ self.data = [
112
+ self.coerce(v.strip()) for v in entrylist.split(",") if v.strip()
113
+ ]
114
+ else:
115
+ self.data = self.coerce(entrylist)
116
+
117
+ def _value(self):
118
+ if isinstance(self.data, (list, tuple)):
119
+ return ",".join(v for v in self.data)
120
+ elif self.data:
121
+ return self.data
122
+ else:
123
+ return ""
@@ -0,0 +1,10 @@
1
+ from wtforms.fields import BooleanField
2
+
3
+
4
+ class SwitchField(BooleanField):
5
+ """
6
+ A wrapper field for ``BooleanField`` that renders as a Bootstrap switch.
7
+ """
8
+
9
+ def __init__(self, label=None, **kwargs):
10
+ super().__init__(label, **kwargs)
@@ -0,0 +1,9 @@
1
+ from wtforms.fields import StringField
2
+
3
+ class TagListField(StringField):
4
+ def process_formdata(self, valuelist):
5
+ if valuelist:
6
+ self.data = [x.strip() for x in valuelist[0].split(",")]
7
+
8
+ def _value(self):
9
+ return ",".join(self.data) if self.data is not None else ""
@@ -0,0 +1,29 @@
1
+ from wtforms import StringField
2
+ from wtforms import PasswordField
3
+ from wtforms import BooleanField
4
+ from wtforms import SubmitField
5
+ from wtforms.validators import ValidationError
6
+ from wtforms.validators import DataRequired
7
+ from wtforms.validators import EqualTo
8
+ from wtforms.validators import Length
9
+
10
+
11
+ class LoginForm:
12
+ username = StringField("Username", validators=[DataRequired()])
13
+ password = PasswordField("Password", validators=[DataRequired()])
14
+ remember_me = BooleanField("Remember Me")
15
+ submit = SubmitField("login")
16
+
17
+
18
+ class RegisterForm:
19
+ username = StringField(
20
+ "Username", validators=[DataRequired(), Length(min=6, max=50)]
21
+ )
22
+ email = StringField("Email", validators=[DataRequired()])
23
+ password = PasswordField(
24
+ "Password", validators=[DataRequired(), Length(min=8, max=50)]
25
+ )
26
+ password_repeat = PasswordField(
27
+ "Repeat Password", validators=[DataRequired(), EqualTo("password")]
28
+ )
29
+ submit = SubmitField("Register")
@@ -0,0 +1,30 @@
1
+ from wtforms.widgets import TextInput
2
+
3
+
4
+ class DatePickerWidget(TextInput):
5
+ """Date picker widget."""
6
+
7
+ def __call__(self, field, **kwargs):
8
+ kwargs.setdefault("data-role", "datepicker")
9
+ kwargs.setdefault("data-date-format", "YYYY-MM-DD")
10
+
11
+ self.date_format = kwargs["data-date-format"]
12
+ return super().__call__(field, **kwargs)
13
+
14
+
15
+ class DateTimePickerWidget(TextInput):
16
+ """Datetime picker widget."""
17
+
18
+ def __call__(self, field, **kwargs):
19
+ kwargs.setdefault("data-role", "datetimepicker")
20
+ kwargs.setdefault("data-date-format", "YYYY-MM-DD HH:mm:ss")
21
+ return super().__call__(field, **kwargs)
22
+
23
+
24
+ class TimePickerWidget(TextInput):
25
+ """Date picker widget."""
26
+
27
+ def __call__(self, field, **kwargs):
28
+ kwargs.setdefault("data-role", "timepicker")
29
+ kwargs.setdefault("data-date-format", "HH:mm:ss")
30
+ return super().__call__(field, **kwargs)
@@ -0,0 +1,4 @@
1
+ from wtforms.widgets import FileInput
2
+
3
+ class ImageInput(FileInput):
4
+ field_flags = {"accept": "image/*"}
@@ -0,0 +1,26 @@
1
+ from wtforms.widgets import Select
2
+ from wtforms.widgets import TextInput
3
+
4
+
5
+ class Select2Widget(Select):
6
+ """Select2 Widget."""
7
+
8
+ def __call__(self, field, **kwargs):
9
+ kwargs.setdefault("data-role", "select2")
10
+ allow_blank = getattr(field, "allow_blank", False)
11
+ if allow_blank and not self.multiple:
12
+ kwargs["data-allow-blank"] = "1"
13
+
14
+ return super().__call__(field, **kwargs)
15
+
16
+
17
+ class Select2TagsWidget(TextInput):
18
+ """Select2Tags Widget."""
19
+
20
+ def __call__(self, field, **kwargs):
21
+ kwargs.setdefault("data-role", "select2-tags")
22
+ kwargs.setdefault(
23
+ "data-allow-duplicate-tags",
24
+ "true" if getattr(field, "allow_duplicates", False) else "false",
25
+ )
26
+ return super().__call__(field, **kwargs)
@@ -26,12 +26,3 @@ def jwt_decode(encoded, key: str, algorithm="HS256"):
26
26
 
27
27
  payload = jwt.decode(encoded, key, algorithm)
28
28
  return payload
29
-
30
-
31
- # try:
32
- # ...
33
- # except Exception as e:
34
- # # import sys
35
- # # print(sys.exc_info())
36
- # # return None,str(e)
37
- # return None
@@ -1,7 +1,10 @@
1
1
  from typing import Optional
2
2
  from sqlalchemy.orm import Mapped
3
3
  from sqlalchemy.orm import mapped_column
4
- from ...random.random_str import secret_token
4
+ import secrets
5
+
6
+ def secret_token():
7
+ return secrets.token_hex(32)
5
8
 
6
9
 
7
10
  class TokenMixin:
@@ -0,0 +1 @@
1
+ from .remove_pycache import remove_pycache
@@ -0,0 +1 @@
1
+
@@ -1,12 +1,10 @@
1
+ import pytest
1
2
  import os
2
3
  import os.path as op
3
4
  import filecmp
4
5
  from python_plugins.random.random_str import rand_sentence
5
- from python_plugins.crypto.file_to_file import encrypt_txtfile
6
- from python_plugins.crypto.file_to_file import decrypt_txtfile
7
- from python_plugins.crypto.file_to_file import encrypt_file
8
- from python_plugins.crypto.file_to_file import decrypt_file
9
-
6
+ from python_plugins.crypto import encrypt_txtfile
7
+ from python_plugins.crypto import decrypt_txtfile
10
8
 
11
9
  tmp_path = op.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
12
10
 
@@ -38,47 +36,51 @@ def _remove_testfiles():
38
36
  safe_delete(path_4)
39
37
  safe_delete(path_5)
40
38
 
41
-
42
39
  def test_crypto_file():
43
40
  create_tmp = _create_temp()
44
41
  if create_tmp:
45
42
  print(create_tmp)
46
43
 
47
- prompt = "test"
48
-
49
44
  with open(path_1, "w") as f:
50
45
  f.write(rand_sentence(30))
51
46
  f.write(rand_sentence(30))
52
47
 
53
- encrypt_txtfile(path_1, path_2, prompt=prompt)
48
+ encrypt_txtfile(path_1, path_2)
49
+ # decrypt_txtfile(path_2)
54
50
  decrypt_txtfile(path_2, path_3)
55
51
  cmp_result = filecmp.cmp(path_1, path_3)
56
52
  assert cmp_result is True
57
53
 
58
- encrypt_file(path_1, path_4, prompt=prompt)
59
- decrypt_file(path_2, path_5)
60
- cmp_result = filecmp.cmp(path_1, path_5)
54
+ _remove_testfiles()
55
+
56
+ def test_crypto_file_with_password():
57
+
58
+ with open(path_1, "w") as f:
59
+ f.write(rand_sentence(30))
60
+ f.write(rand_sentence(30))
61
+
62
+ password = rand_sentence(10)
63
+ encrypt_txtfile(path_1, path_2, password=password)
64
+ with pytest.raises(Exception):
65
+ decrypt_txtfile(path_2, path_3,password="")
66
+ decrypt_txtfile(path_2, path_3, password=password)
67
+ cmp_result = filecmp.cmp(path_1, path_3)
61
68
  assert cmp_result is True
62
69
 
63
70
  _remove_testfiles()
64
71
 
65
- # pytest with `input()` must using `-s`
72
+ # pytest with `input()` must using `-s`
66
73
  # pytest tests\test_crypt_file.py::test_crypto_file_with_password -s
67
- def _test_crypto_file_with_password():
68
- prompt = "test"
74
+ @pytest.mark.skip
75
+ def test_crypto_file_with_input_password():
69
76
 
70
77
  with open(path_1, "w") as f:
71
78
  f.write(rand_sentence(30))
72
79
  f.write(rand_sentence(30))
73
80
 
74
- encrypt_txtfile(path_1, path_2, accept_password=True)
81
+ encrypt_txtfile(path_1, path_2, password='[input]')
75
82
  decrypt_txtfile(path_2, path_3)
76
83
  cmp_result = filecmp.cmp(path_1, path_3)
77
84
  assert cmp_result is True
78
85
 
79
- encrypt_file(path_1, path_4, accept_password=True)
80
- decrypt_file(path_2, path_5)
81
- cmp_result = filecmp.cmp(path_1, path_5)
82
- assert cmp_result is True
83
-
84
86
  _remove_testfiles()
@@ -56,27 +56,8 @@ class TestStr2List:
56
56
  password = rand_letter(16)
57
57
  encrypted_list = encrypt_str_to_list(s, password)
58
58
  with pytest.raises(Exception):
59
- s1 = decrypt_list_to_str(encrypted_list)
59
+ s1 = decrypt_list_to_str([None] + encrypted_list[1:])
60
60
  s2 = decrypt_list_to_str(encrypted_list, password)
61
61
  assert s == s2
62
62
  s3 = decrypt_list_to_str([None] + encrypted_list[1:], password)
63
63
  assert s == s3
64
-
65
- def test_encrypt_decrypt_with_prefix(self):
66
- s = rand_sentence(random.randint(10, 100))
67
- prefix = rand_letter(16)
68
- encrypted_list = encrypt_str_to_list(s, prefix=prefix)
69
- with pytest.raises(Exception):
70
- s1 = decrypt_list_to_str(encrypted_list)
71
- s2 = decrypt_list_to_str(encrypted_list, prefix=prefix)
72
- assert s == s2
73
-
74
- def test_encrypt_decrypt_with_password_prefix(self):
75
- s = rand_sentence(random.randint(10, 100))
76
- password = rand_letter(16)
77
- prefix = rand_letter(16)
78
- encrypted_list = encrypt_str_to_list(s, password, prefix)
79
- with pytest.raises(Exception):
80
- s1 = decrypt_list_to_str(encrypted_list, prefix=prefix)
81
- s2 = decrypt_list_to_str(encrypted_list, password, prefix)
82
- assert s == s2
@@ -0,0 +1,65 @@
1
+ from wtforms.form import Form
2
+ from python_plugins.forms.fields import JSONField
3
+ from python_plugins.forms.fields import DateTimeField
4
+ from python_plugins.forms.mixins.user import LoginForm
5
+ from python_plugins.forms.mixins.user import RegisterForm
6
+
7
+
8
+ class DummyPostData(dict):
9
+ def getlist(self, key):
10
+ v = self[key]
11
+ if not isinstance(v, (list, tuple)):
12
+ v = [v]
13
+ return v
14
+
15
+
16
+ class UserLoginForm(Form, LoginForm):
17
+ pass
18
+
19
+
20
+ class UserRegisterForm(Form, RegisterForm):
21
+ pass
22
+
23
+
24
+ def test_fields():
25
+ class F(Form):
26
+ json_field = JSONField()
27
+ datetime_field = DateTimeField()
28
+
29
+ formdata = DummyPostData(
30
+ json_field="[1,2,3]",
31
+ datetime_field="2000-01-01 12:12:12",
32
+ )
33
+
34
+ f = F(formdata)
35
+ assert f.validate()
36
+
37
+ json_field_text = f.json_field()
38
+ assert '<textarea id="json_field" name="json_field">' in json_field_text
39
+ assert "[1, 2, 3]</textarea>" in json_field_text
40
+
41
+ datetime_field_text = f.datetime_field()
42
+ assert "<input" in datetime_field_text
43
+ assert (
44
+ 'data-date-format="YYYY-MM-DD HH:mm:ss" data-role="datetimepicker"'
45
+ in datetime_field_text
46
+ )
47
+ assert 'value="2000-01-01 12:12:12"' in datetime_field_text
48
+
49
+
50
+ def test_user_form():
51
+ login_form = UserLoginForm()
52
+
53
+ for k in login_form:
54
+ # print(k.label())
55
+ # print(k())
56
+ assert k() is not None
57
+
58
+ assert "username" in login_form.username()
59
+
60
+ register_form = UserRegisterForm()
61
+
62
+ for k in register_form:
63
+ # print(k.label())
64
+ # print(k())
65
+ assert k() is not None
@@ -1,11 +1,11 @@
1
1
  import pytest
2
2
 
3
- from python_plugins.utils.remove_pycache import remove_pycache
3
+ from python_plugins.utils import remove_pycache
4
4
 
5
5
  @pytest.mark.skip
6
6
  def test_remove_pycache():
7
7
  remove_pycache("./tests")
8
8
 
9
- @pytest.mark.skip
9
+ @pytest.mark.skip()
10
10
  def test_remove_pycache():
11
11
  remove_pycache()
@@ -1 +0,0 @@
1
- __version__ = "0.1.7"
@@ -1 +0,0 @@
1
- from .utils.remove_pycache import remove_pycache
@@ -1 +0,0 @@
1
- from .fernet import generate_fernet_key,fernet_encrypt,fernet_decrypt
@@ -1,112 +0,0 @@
1
- from .str_to_list import encrypt_bytes_to_list
2
- from .str_to_list import encrypt_str_to_list
3
- from .str_to_list import decrypt_list_to_bytes
4
- from .str_to_list import decrypt_list_to_str
5
- from getpass import getpass
6
-
7
-
8
- def bytes_from_file(fin) -> bytes:
9
- with open(fin, "rb") as f:
10
- s = f.read()
11
- return s
12
-
13
-
14
- def bytes_to_file(s: bytes, fout):
15
- with open(fout, "wb") as f:
16
- f.write(s)
17
-
18
-
19
- def str_from_txtfile(fin) -> str:
20
- with open(fin, encoding="utf-8") as f:
21
- s = f.read()
22
- return s
23
-
24
-
25
- def str_to_txtfile(s: str, fout):
26
- with open(fout, "w", encoding="utf-8") as f:
27
- f.write(s)
28
-
29
-
30
- def bytes_to_file(s, fout):
31
- with open(fout, "wb") as f:
32
- f.write(s)
33
-
34
-
35
- def encrypt_txt(s: str, prompt=None, accept_password=False):
36
- if not prompt:
37
- prompt = input("input prompt=")
38
- password = None
39
- if accept_password:
40
- password = getpass("input password=")
41
- if password:
42
- encrypted_list = encrypt_str_to_list(s, password)
43
- encrypted_list[0] = "-"
44
- else:
45
- encrypted_list = encrypt_str_to_list(s)
46
- s2 = "\n".join([prompt] + encrypted_list)
47
- return s2
48
-
49
-
50
- def decrypt_txt(s: str):
51
- encrypted_list = s.split("\n")
52
- prompt = encrypted_list[0]
53
- if encrypted_list[1] == "-":
54
- print(prompt)
55
- password = getpass("input password=")
56
- s2 = decrypt_list_to_str(encrypted_list[1:], password)
57
- else:
58
- s2 = decrypt_list_to_str(encrypted_list[1:])
59
-
60
- return s2
61
-
62
-
63
- def encrypt_txtfile(fin, fout, prompt=None, accept_password=False):
64
- s = str_from_txtfile(fin)
65
- s2 = encrypt_txt(s, prompt, accept_password)
66
- str_to_txtfile(s2, fout)
67
-
68
-
69
- def decrypt_txtfile(fin, fout):
70
- s = str_from_txtfile(fin)
71
- s2 = decrypt_txt(s)
72
- str_to_txtfile(s2, fout)
73
-
74
-
75
- def encrypt_bytes(s: bytes, prompt=None, accept_password=False):
76
- if not prompt:
77
- prompt = input("input prompt=")
78
- password = None
79
- if accept_password:
80
- password = getpass("input password=")
81
- if password:
82
- encrypted_list = encrypt_bytes_to_list(s, password)
83
- encrypted_list[0] = "-"
84
- else:
85
- encrypted_list = encrypt_bytes_to_list(s)
86
- s2 = "\n".join([prompt] + encrypted_list)
87
- return s2
88
-
89
-
90
- def decrypt_bytes(s: str):
91
- encrypted_list = s.split("\n")
92
- prompt = encrypted_list[0]
93
- if encrypted_list[1] == "-":
94
- print(prompt)
95
- password = getpass("input password=")
96
- s2 = decrypt_list_to_bytes(encrypted_list[1:], password)
97
- else:
98
- s2 = decrypt_list_to_bytes(encrypted_list[1:])
99
-
100
- return s2
101
-
102
-
103
- def encrypt_file(fin, fout, prompt=None, accept_password=False):
104
- s = bytes_from_file(fin)
105
- s2 = encrypt_bytes(s, prompt, accept_password)
106
- str_to_txtfile(s2, fout)
107
-
108
-
109
- def decrypt_file(fin, fout):
110
- s = str_from_txtfile(fin)
111
- s2 = decrypt_bytes(s)
112
- bytes_to_file(s2, fout)