MainShortcuts2 2.8.3__tar.gz → 2.8.5__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 (56) hide show
  1. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/PKG-INFO +1 -1
  2. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/pyproject.toml +1 -1
  3. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/_module_info.py +1 -1
  4. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/advanced.py +31 -0
  5. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/aiohttp_ex/web/__init__.py +9 -5
  6. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/pathlib_ex.py +41 -9
  7. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ms2dat1.py +9 -2
  8. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/str.py +14 -15
  9. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/utils.py +68 -0
  10. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/README.md +0 -0
  11. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/__init__.py +0 -0
  12. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/__main__.py +0 -0
  13. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/_any2json_regs.py +0 -0
  14. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/_ms2app_regs.py +0 -0
  15. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/_ms2dat_auto.py +0 -0
  16. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/any2json.py +0 -0
  17. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/base.py +0 -0
  18. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/gigachat.py +0 -0
  19. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/github.py +0 -0
  20. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/russian_trusted_root_ca_pem.crt +0 -0
  21. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/russian_trusted_sub_ca_pem.crt +0 -0
  22. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/api/webdav.py +0 -0
  23. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/cfg.py +0 -0
  24. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/core.py +0 -0
  25. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/core_config.py +0 -0
  26. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/dict.py +0 -0
  27. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/dir.py +0 -0
  28. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/__init__.py +0 -0
  29. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/aiohttp_ex/web/__main__.py +0 -0
  30. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/datetime_ex.py +0 -0
  31. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/pil_ex.py +0 -0
  32. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/psutil_ex.py +0 -0
  33. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/sqlite_ex.py +0 -0
  34. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ex/urlparse_ex.py +0 -0
  35. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/file.py +0 -0
  36. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/gui_scripts/__init__.py +0 -0
  37. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/gui_scripts/ms2_hash_gen.py +0 -0
  38. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/gui_scripts/utils.py +0 -0
  39. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/java_ext/__init__.py +0 -0
  40. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/java_ext/ms2ext.py +0 -0
  41. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/json.py +0 -0
  42. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/linux.py +0 -0
  43. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/list.py +0 -0
  44. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ms2app.py +0 -0
  45. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/ms2hash.py +0 -0
  46. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/path.py +0 -0
  47. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/proc.py +0 -0
  48. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/regex.py +0 -0
  49. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/special_chars.py +0 -0
  50. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/sql/_sql_base.py +0 -0
  51. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/sql/mysql.py +0 -0
  52. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/sql/postgresql.py +0 -0
  53. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/sql/sqlite.py +0 -0
  54. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/term.py +0 -0
  55. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/types.py +0 -0
  56. {mainshortcuts2-2.8.3 → mainshortcuts2-2.8.5}/src/MainShortcuts2/win.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MainShortcuts2
3
- Version: 2.8.3
3
+ Version: 2.8.5
4
4
  Summary: Сокращение и улучшение функций + консольные утилиты
5
5
  Author: MainPlay TG
6
6
  Author-email: xbox.roman6666666666@gmail.com
@@ -1,5 +1,5 @@
1
1
  [tool.poetry]
2
- version = "2.8.3"
2
+ version = "2.8.5"
3
3
  name = "MainShortcuts2"
4
4
  description = "Сокращение и улучшение функций + консольные утилиты"
5
5
  authors = ["MainPlay TG <xbox.roman6666666666@gmail.com>"]
@@ -1,2 +1,2 @@
1
1
  name = 'mainshortcuts2'
2
- version = '2.8.3'
2
+ version = '2.8.5'
@@ -1110,3 +1110,34 @@ class NetBroadcastReceiver(_ServerBase):
1110
1110
  break
1111
1111
  self.recv()
1112
1112
  self._stopping = False
1113
+
1114
+
1115
+ class SimpleBcrypt:
1116
+ """Упрощение методов `bcrypt`. Библиотека `bcrypt` должна быть доступна
1117
+ ```
1118
+ pip install -U bcrypt
1119
+ ```"""
1120
+
1121
+ def __init__(self):
1122
+ import bcrypt
1123
+ self._b = bcrypt
1124
+ self.encoding = "utf-8"
1125
+ self.salt_prefix = b"2b"
1126
+ self.salt_rounds = 12
1127
+
1128
+ def _to_bytes(self, s: bytes | str) -> bytes:
1129
+ if isinstance(s, str):
1130
+ return s.encode(self.encoding)
1131
+ return s
1132
+
1133
+ def gen_salt(self):
1134
+ """Сгенерировать соль для хеширования"""
1135
+ return self._b.gensalt(self.salt_rounds, self.salt_prefix)
1136
+
1137
+ def hash_pwd(self, pwd: bytes | str):
1138
+ """Хешировать пароль"""
1139
+ return self._b.hashpw(self._to_bytes(pwd), self.gen_salt())
1140
+
1141
+ def check_pwd(self, pwd: bytes | str, hashed_pwd: bytes | str):
1142
+ """Проверить пароль"""
1143
+ return self._b.checkpw(self._to_bytes(pwd), self._to_bytes(hashed_pwd))
@@ -24,11 +24,11 @@ def wrap_handler(app: "Application", handler: Handler):
24
24
  if isinstance(resp, int): # Код статуса
25
25
  resp = Response(status=resp)
26
26
  elif isinstance(resp, ApiResult): # Результат API обработчика
27
- resp = resp.make_resp(req.content_type)
27
+ resp = resp.make_resp(req.headers.get("Accept"))
28
28
  elif isinstance(resp, PATH_TYPES): # Локальный файл
29
29
  resp = FileResponse(resp)
30
30
  except ApiResult as exc: # Результат API исключения
31
- resp = exc.make_resp(req.content_type)
31
+ resp = exc.make_resp(req.headers.get("Accept"))
32
32
  except Exception as exc:
33
33
  app.logger.exception("Failed to process request", exc_info=exc)
34
34
  resp = Response(status=500, reason="Internal server error")
@@ -167,12 +167,16 @@ class ApiResult(BaseException):
167
167
  from MainShortcuts2 import ms2dat1
168
168
  return "application/x-ms2dat1", ms2dat1.dumps(self.to_dict())
169
169
 
170
- def make_resp(self, content_type=None):
170
+ def make_resp(self, accept_header: str = None):
171
171
  """Создать ответ в указаном формате, по умолчанию JSON"""
172
+ use_ms2dat, use_yaml = False, False
173
+ if accept_header:
174
+ use_ms2dat = "application/x-ms2dat1" in accept_header
175
+ use_yaml = ("application/yaml" in accept_header) and ("application/json" not in accept_header)
172
176
  try:
173
- if content_type == "application/x-ms2dat1":
177
+ if use_ms2dat:
174
178
  ctype, body = self._to_ms2dat1()
175
- elif content_type == "application/yaml":
179
+ elif use_yaml:
176
180
  ctype, body = self._to_yaml()
177
181
  else: # Если запрошенный формат не поддерживается
178
182
  ctype, body = self._to_json()
@@ -1,6 +1,7 @@
1
1
  import os
2
2
  import pathlib
3
3
  import shutil
4
+ import typing
4
5
  from MainShortcuts2 import ms
5
6
  from os import fspath
6
7
  from stat import S_ISDIR, S_ISREG
@@ -12,7 +13,7 @@ class Path(pathlib.Path):
12
13
  """Объект `ms.path.Path`"""
13
14
  return ms.path.Path(self)
14
15
 
15
- def size(self, recursive=False, **walk_kw):
16
+ def size(self, recursive=False, **walk_kw) -> int:
16
17
  """Вычислить размер файла/папки"""
17
18
  st = self.stat()
18
19
  if S_ISREG(st.st_mode):
@@ -56,7 +57,7 @@ class Path(pathlib.Path):
56
57
  def _get_write_path(self):
57
58
  """tmp,real"""
58
59
  real = self.resolve()
59
- tmp = real
60
+ tmp = real.with_name(self.name + ".tmp" + ms.utils.randstr(4))
60
61
  while tmp.exists():
61
62
  tmp = real.with_name(self.name + ".tmp" + ms.utils.randstr(4))
62
63
  return tmp, real
@@ -71,18 +72,24 @@ class Path(pathlib.Path):
71
72
  kw.setdefault("encoding", "utf-8")
72
73
  """Записать текст в файл"""
73
74
  tmp, real = self._get_write_path()
74
- with tmp.open("w", **kw) as f:
75
- result = f.write(data)
76
- if not tmp.samefile(real):
75
+ try:
76
+ with tmp.open("w", **kw) as f:
77
+ result = f.write(data)
77
78
  tmp.replace(real)
79
+ except:
80
+ tmp.unlink(True)
81
+ raise
78
82
  return result
79
83
 
80
- def write_bytes(self, data, **kw) -> int:
84
+ def write_bytes(self, data: bytes, **kw) -> int:
81
85
  tmp, real = self._get_write_path()
82
- with tmp.open("wb", **kw) as f:
83
- result = f.write(data)
84
- if not tmp.samefile(real):
86
+ try:
87
+ with tmp.open("wb", **kw) as f:
88
+ result = f.write(data)
85
89
  tmp.replace(real)
90
+ except:
91
+ tmp.unlink(True)
92
+ raise
86
93
  return result
87
94
 
88
95
  def read_json(self, **kw):
@@ -140,3 +147,28 @@ class Path(pathlib.Path):
140
147
  yield from [os.path.join(root, i) for i in filenames]
141
148
  else:
142
149
  yield from os.listdir(self)
150
+ if not typing.TYPE_CHECKING:
151
+ def samefile(self, other_path):
152
+ """Добавление проверки пути к файлу, чтобы не выполнять stat лишний раз"""
153
+ if os.fspath(self) == os.fspath(other_path):
154
+ return True
155
+ return super().samefile(other_path)
156
+
157
+ def samestat(self, st2: os.stat_result):
158
+ """Аналогично `.samefile`, но принимает `stat_result` вместо пути"""
159
+ st1 = self.stat()
160
+ return st1.st_dev == st2.st_dev and st1.st_ino == st2.st_ino
161
+
162
+ def write_ms2dat(self, data, **kw):
163
+ """Сохранить данные в последней версии формата MS2Dat"""
164
+ ms.ms2dat.write_file(data, self, **kw)
165
+
166
+ def write_ms2dat_v1(self, data, ms2dat_inst=None, **kw):
167
+ """Сохранить данные в формате MS2Dat v1"""
168
+ if ms2dat_inst is None:
169
+ ms2dat_inst = ms.ms2dat_v1.inst
170
+ ms2dat_inst.write_file(data, self, **kw)
171
+
172
+ def read_ms2dat(self, **kw):
173
+ """Прочитать данные в формате MS2Dat"""
174
+ ms.ms2dat.read_file(self, **kw)
@@ -6,6 +6,7 @@ import struct
6
6
  import typing
7
7
  import uuid
8
8
  from io import BytesIO
9
+ from MainShortcuts2.ex.pathlib_ex import Path
9
10
  from MainShortcuts2.utils import int_size_unsigned
10
11
  HASH_NAMES = None, "sha256", "sha3-256", "sha512"
11
12
  HASH_SIZES = 0, 32, 32, 64
@@ -516,8 +517,14 @@ class MS2Dat1:
516
517
 
517
518
  def write_file(self, obj, path, **kw):
518
519
  """Сохранить объект в локальный файл"""
519
- with open(path, "wb") as f:
520
- self.dump(obj, f, **kw)
520
+ tmp, real = Path(path)._get_write_path()
521
+ try:
522
+ with tmp.open("wb") as f:
523
+ self.dump(obj, f, **kw)
524
+ tmp.replace(real)
525
+ except:
526
+ tmp.unlink(True)
527
+ raise
521
528
 
522
529
 
523
530
  class MS2Dat1EncryptExample(MS2Dat1):
@@ -1,14 +1,10 @@
1
1
  """Работа со строками"""
2
- from .core import ms
3
- from typing import *
2
+ import typing
4
3
 
5
4
 
6
- def list2str(a: Union[Iterable]) -> list:
5
+ def list2str(a: typing.Iterable[str]):
7
6
  """Преобразовать каждый элемент списка в строку"""
8
- b = []
9
- for i in a:
10
- b.append(str(i))
11
- return b
7
+ return [str(i) for i in a]
12
8
 
13
9
 
14
10
  def dict2str(a: dict) -> dict:
@@ -19,13 +15,10 @@ def dict2str(a: dict) -> dict:
19
15
  return b
20
16
 
21
17
 
22
- class _Replace:
18
+ class replace:
23
19
  """Функции для замены текста"""
24
-
25
- def __init__(self):
26
- pass
27
-
28
- def multi(self, text: str, d: dict = None, **kw) -> str:
20
+ @classmethod
21
+ def multi(cls, text: str, d: dict = None, **kw) -> str:
29
22
  """Мульти-замена {"что заменить":"чем заменить"}"""
30
23
  if not d is None:
31
24
  kw.update(d)
@@ -34,7 +27,8 @@ class _Replace:
34
27
  t = t.replace(k, str(v))
35
28
  return t
36
29
 
37
- def all(self, text: str, fr: str, to: str) -> str:
30
+ @classmethod
31
+ def all(cls, text: str, fr: str, to: str) -> str:
38
32
  """Замена пока заменяемый текст не исчезнет"""
39
33
  t = str(text)
40
34
  a = str(fr)
@@ -46,4 +40,9 @@ class _Replace:
46
40
  return t
47
41
 
48
42
 
49
- replace = _Replace()
43
+ def join_list(lst: typing.Iterable[str], midsep=", ", lastsep=" и "):
44
+ """Объединить список в строку с отличающимся последним разделителем"""
45
+ lst = [str(i) for i in lst]
46
+ if len(lst) < 3:
47
+ return lastsep.join(lst)
48
+ return midsep.join(lst[:-1]) + lastsep + lst[-1]
@@ -1,5 +1,6 @@
1
1
  """Различные утилиты, иногда требующие сторонних модулей"""
2
2
  import atexit
3
+ import base64
3
4
  import builtins
4
5
  import importlib
5
6
  import logging
@@ -7,6 +8,7 @@ import os
7
8
  import sys
8
9
  import time
9
10
  import typing
11
+ import uuid as UuidModule
10
12
  from .core import ms
11
13
  from contextlib import ExitStack
12
14
  from functools import wraps
@@ -1208,3 +1210,69 @@ class FilterGetAttr(Filter):
1208
1210
  class FilterGetItem(FilterGetAttr):
1209
1211
  def __call__(self, obj):
1210
1212
  return obj[self.name]
1213
+
1214
+
1215
+ gen_uuid = UuidModule.uuid4
1216
+ if not typing.TYPE_CHECKING:
1217
+ # Выбрать быстрейшую функцию
1218
+ for i in (8, 7, 6):
1219
+ j = f"uuid{i}"
1220
+ if hasattr(UuidModule, j):
1221
+ gen_uuid = getattr(UuidModule, j)
1222
+ break
1223
+ del i, j
1224
+
1225
+
1226
+ def short_b64encode(s: bytes, **kw):
1227
+ """Кодирование в Base64 с удалением заполнителей"""
1228
+ return base64.b64encode(s, **kw).rstrip(b"=")
1229
+
1230
+
1231
+ def short_b64decode(s: bytes, **kw):
1232
+ """Декодирование Base64 с восстановлением заполнителей"""
1233
+ n = -len(s) % 4
1234
+ if n:
1235
+ suffix = ("=" if isinstance(s, str) else b"=") * n
1236
+ return base64.b64decode(s + suffix, **kw)
1237
+ return base64.b64decode(s, **kw)
1238
+
1239
+
1240
+ def short_urlsafe_b64encode(s: bytes):
1241
+ """Аналогично `short_b64encode`, но безопасен для URL"""
1242
+ return base64.urlsafe_b64encode(s).rstrip(b"=")
1243
+
1244
+
1245
+ def short_urlsafe_b64decode(s: bytes):
1246
+ """Аналогично `short_b64decode`, но безопасен для URL"""
1247
+ n = -len(s) % 4
1248
+ if n:
1249
+ suffix = ("=" if isinstance(s, str) else b"=") * n
1250
+ return base64.urlsafe_b64decode(s + suffix)
1251
+ return base64.urlsafe_b64decode(s)
1252
+
1253
+
1254
+ def uuid2bytes(uuid):
1255
+ """Конвертировать UUID в байты"""
1256
+ if isinstance(uuid, bytes):
1257
+ return uuid
1258
+ return uuid2obj(uuid).bytes
1259
+
1260
+
1261
+ def uuid2obj(uuid):
1262
+ """Конвертировать UUID в объект"""
1263
+ if isinstance(uuid, UuidModule.UUID):
1264
+ return uuid
1265
+ if isinstance(uuid, bytes):
1266
+ return UuidModule.UUID(bytes=uuid)
1267
+ if isinstance(uuid, memoryview):
1268
+ return UuidModule.UUID(bytes=uuid.tobytes())
1269
+ if isinstance(uuid, str):
1270
+ return UuidModule.UUID(hex=uuid)
1271
+ raise TypeError("Invalid uuid type")
1272
+
1273
+
1274
+ def uuid2str(uuid):
1275
+ """Конвертировать UUID в строку"""
1276
+ if isinstance(uuid, str):
1277
+ return uuid
1278
+ return str(uuid2obj(uuid))
File without changes