swc-utils 0.0.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Davis_Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: swc_utils
3
+ Version: 0.0.1
4
+ Summary: Provides utility functions for SWC projects
5
+ Author-email: Davis_Software <davissoftware6@gmail.com>
6
+ Project-URL: Homepage, https://projects.software-city.org/
7
+ Project-URL: Issues, https://projects.software-city.org/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: Flask==3.0.3
15
+ Requires-Dist: Flask-SQLAlchemy==3.1.1
16
+
17
+ ### SWC Utils
18
+
19
+ This repository contains a collection of utilities for SWC projects.
@@ -0,0 +1,3 @@
1
+ ### SWC Utils
2
+
3
+ This repository contains a collection of utilities for SWC projects.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "swc_utils"
7
+ version = "0.0.1"
8
+ authors = [
9
+ { name="Davis_Software", email="davissoftware6@gmail.com" },
10
+ ]
11
+ description = "Provides utility functions for SWC projects"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "Flask==3.0.3",
21
+ "Flask-SQLAlchemy==3.1.1"
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://projects.software-city.org/"
26
+ Issues = "https://projects.software-city.org/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,2 @@
1
+ from .connection_profile import ConnectionProfile
2
+ from .database_connection import connect_to_database
@@ -0,0 +1,33 @@
1
+ class ConnectionProfile:
2
+ def __init__(self, host: str, port: int, database: str, username: str, password: str, sql_type: str):
3
+ self.mysql_host = host
4
+ self.mysql_port = port
5
+ self.mysql_database = database
6
+ self.mysql_username = username
7
+ self.mysql_password = password
8
+ self.sql_type = sql_type
9
+
10
+ @property
11
+ def connection_uri(self):
12
+ if self.sql_type == "sqlite":
13
+ uri_elements = [
14
+ 'sqlite:///',
15
+ self.mysql_database
16
+ ]
17
+ elif self.sql_type == "mysql":
18
+ uri_elements = [
19
+ 'mysql://',
20
+ self.mysql_username,
21
+ ':',
22
+ self.mysql_password,
23
+ '@',
24
+ self.mysql_host,
25
+ ':',
26
+ self.mysql_port,
27
+ '/',
28
+ self.mysql_database
29
+ ]
30
+ else:
31
+ raise TypeError("No such SQLType", self.sql_type)
32
+
33
+ return ''.join(uri_elements)
@@ -0,0 +1,13 @@
1
+ from flask import Flask
2
+ from .connection_profile import ConnectionProfile
3
+
4
+
5
+ def connect_to_database(app: Flask, conn: ConnectionProfile, extra_db: dict[str, ConnectionProfile] = None):
6
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
7
+ app.config["SQLALCHEMY_DATABASE_URI"] = conn.connection_uri
8
+
9
+ if extra_db is not None:
10
+ for key, value in extra_db.items():
11
+ extra_db[key] = value.connection_uri
12
+
13
+ app.config['SQLALCHEMY_BINDS'] = extra_db
@@ -0,0 +1 @@
1
+ from .generator_utils import generator_from_callback_consumer
@@ -0,0 +1,26 @@
1
+ import time
2
+ import threading
3
+
4
+
5
+ def generator_from_callback_consumer(consumer: callable, args: tuple = None, callback_name: str = "monitor", kwargs: dict = None):
6
+ args = args or ()
7
+ kwargs = kwargs or {}
8
+
9
+ data = None
10
+
11
+ def monitor(new_data):
12
+ nonlocal data
13
+ data = new_data
14
+
15
+ def thread():
16
+ kwargs[callback_name] = monitor
17
+ consumer(*args, **kwargs)
18
+ thread = threading.Thread(target=thread, daemon=True)
19
+
20
+ thread.start()
21
+ while thread.is_alive():
22
+ time.sleep(0.1)
23
+ if data is not None:
24
+ yield data
25
+
26
+ yield data
@@ -0,0 +1,2 @@
1
+ from .config import Config
2
+ from .route_loader import load_routes
@@ -0,0 +1,29 @@
1
+ class Config:
2
+ def __init__(self, config_file):
3
+ self.config_file = config_file
4
+ self.__config = self.__read_config()
5
+
6
+ def __read_config(self):
7
+ config = {}
8
+ with open(self.config_file, 'r', encoding="utf-8") as f:
9
+ for line in f:
10
+ line = line.strip()
11
+ if line and not line.startswith('#'):
12
+ key, value = line.split('=')
13
+ config[key] = value
14
+ return config
15
+
16
+ def __getitem__(self, item):
17
+ return self.get(item)
18
+
19
+ def get(self, key, default=None):
20
+ return self.__config.get(key, default)
21
+
22
+ def get_bool(self, key, default=None):
23
+ return self.get(key, default) in ['True', 'true', '1']
24
+
25
+ def get_list(self, key, default=None):
26
+ return self.get(key, default).split(',')
27
+
28
+ def get_int(self, key, default=None):
29
+ return int(self.get(key, default))
@@ -0,0 +1,13 @@
1
+ import os
2
+ import importlib
3
+
4
+
5
+ def load_routes(working_dir: str, route_path: str, recursive: bool = True):
6
+ for file in os.listdir(os.path.join(working_dir, route_path)):
7
+ if os.path.isdir(os.path.join(working_dir, route_path, file)) and recursive:
8
+ load_routes(working_dir, os.path.join(route_path, file), recursive)
9
+
10
+ if file.endswith(".py"):
11
+ importlib.import_module(
12
+ os.path.join(route_path, file).replace("\\", ".").replace("/", ".")[:-3],
13
+ )
@@ -0,0 +1,3 @@
1
+ from .auth_manager import auth_required, admin_required, check_admin, check_auth, check_permission
2
+ from .adv_responses import send_binary_image
3
+ from .request_codes import RequestCode
@@ -0,0 +1,18 @@
1
+
2
+ from flask import make_response, send_file
3
+
4
+ from .request_codes import RequestCode
5
+
6
+
7
+ def send_binary_image(data, content_type="image/jpeg", cache_control=3600):
8
+ if data is None:
9
+ return make_response(
10
+ send_file("static/img/noimage.png"),
11
+ # RequestCode.ClientError.NotFound
12
+ RequestCode.Success.OK
13
+ )
14
+
15
+ resp = make_response(data, RequestCode.Success.OK)
16
+ resp.headers.set("Content-Type", content_type)
17
+ resp.cache_control.max_age = cache_control
18
+ return resp
@@ -0,0 +1,43 @@
1
+ from functools import wraps
2
+ from .request_codes import RequestCode
3
+ from flask import session, request, abort, redirect
4
+
5
+
6
+ def check_auth():
7
+ return session.get("logged_in") and session.get("user")
8
+
9
+
10
+ def auth_required(func):
11
+ @wraps(func)
12
+ def check(*args, **kwargs):
13
+ if check_auth():
14
+ return func(*args, **kwargs)
15
+ return redirect(f"/login?redirect={request.path}")
16
+
17
+ return check
18
+
19
+
20
+ def check_admin():
21
+ return session.get("user").get("admin", False) or session.get("admin", False)
22
+
23
+
24
+ def check_permission(permission):
25
+ perms = session.get("user").get("permissions") or []
26
+ perms.extend(session.get("permissions", []))
27
+
28
+ if perms is None:
29
+ return False
30
+ if "*" in perms:
31
+ return True
32
+
33
+ return permission in perms
34
+
35
+
36
+ def admin_required(func):
37
+ @wraps(func)
38
+ def check(*args, **kwargs):
39
+ if check_admin():
40
+ return func(*args, **kwargs)
41
+ return abort(RequestCode.ClientError.Unauthorized)
42
+
43
+ return check
@@ -0,0 +1,89 @@
1
+ class RequestCode:
2
+ """
3
+ Represents a collection of all possible status codes
4
+ of a server response. They are ordered by category,
5
+ which makes them more readable for other developers.
6
+ Instead of writing 200, you could type StopCodes.Success.OK
7
+ and everyone reading your code will know that the response
8
+ was handled successfully.
9
+
10
+ For more information on the different response codes, visit:
11
+ https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
12
+ """
13
+
14
+ class Info:
15
+ Continue = 200
16
+ SwitchingProtocols = 101
17
+ Processing = 102
18
+ EarlyHints = 103
19
+
20
+ class Success:
21
+ OK = 200
22
+ Created = 201
23
+ Accepted = 202
24
+ NAuthInfo = 203
25
+ NoContent = 204
26
+ ResetContent = 205
27
+ PartialContent = 206
28
+ MultiStatus = 207
29
+ AlreadyReported = 208
30
+ IMUsed = 226
31
+
32
+ class Redirect:
33
+ MultipleChoices = 300
34
+ MovedPermanently = 301
35
+ MovedTemporarily = 302
36
+ SeeOther = 303
37
+ NotModified = 304
38
+ UseProxy = 305
39
+ SwitchProxy = 306
40
+ TemporaryRedirect = 307
41
+ PermanentRedirect = 308
42
+
43
+ class ClientError:
44
+ BadRequest = 400
45
+ Unauthorized = 401
46
+ PaymentRequired = 402
47
+ Forbidden = 403
48
+ NotFound = 404
49
+ MethodNotAllowed = 405
50
+ NotAcceptable = 406
51
+ ProxyAuthRequired = 407
52
+ RequestTimeout = 408
53
+ Conflict = 409
54
+ Gone = 410
55
+ LengthRequired = 411
56
+ PreconditionFailed = 412
57
+ PayloadTooLarge = 413
58
+ URITooLong = 414
59
+ UnsupportedMediaType = 415
60
+ RangeNotSatisfiable = 416
61
+ ImATeapot = 418
62
+ ExpectationFailed = 417
63
+ PolicyNotFulfilled = 420
64
+ MisdirectedRequest = 421
65
+ UnprocessableEntity = 422
66
+ Locked = 423
67
+ FailedDependency = 424
68
+ TooEarly = 425
69
+ UpgradeRequired = 426
70
+ PreconditionRequired = 428
71
+ TooManyRequests = 429
72
+ RequestHeaderFieldsTooLarge = 431
73
+ NoResponse = 444
74
+ ClientCloseRequest = 499
75
+ UnavailableForLegalReasons = 451
76
+
77
+ class ServerError:
78
+ InternalServerError = 500
79
+ NotImplemented = 501
80
+ BadGateway = 502
81
+ ServiceUnavailable = 503
82
+ GatewayTimeout = 504
83
+ HTTPVersionNotSupported = 505
84
+ VariantsAlsoNegotiates = 506
85
+ InsufficientStorage = 507
86
+ LoopDetected = 508
87
+ BandwidthLimitExceeded = 509
88
+ NotExtended = 510
89
+ NetworkAuthRequired = 511
@@ -0,0 +1 @@
1
+ from .wsl_compatability import get_wsl_path, make_wsl_command, get_local_wsl_temp_dir
@@ -0,0 +1,24 @@
1
+ from ..tools.config import Config
2
+
3
+
4
+ def get_wsl_path(config: Config, path: str):
5
+ if not config.get_bool("USE_WSL", False):
6
+ return path
7
+
8
+ path_parts = path.split(":\\")
9
+ return f"/mnt/{path_parts[0].lower()}/" + path_parts[1].replace('\\', '/')
10
+
11
+
12
+ def make_wsl_command(config: Config, command: list):
13
+ if not config.get_bool("USE_WSL", False):
14
+ return command
15
+
16
+ dist = config["WSL_DISTRO"]
17
+ return ["wsl", "-d", dist, *command]
18
+
19
+
20
+ def get_local_wsl_temp_dir(config: Config):
21
+ if not config.get_bool("USE_WSL", False):
22
+ return "/tmp/"
23
+
24
+ return f"\\\\wsl.localhost\\{config['WSL_DISTRO']}\\tmp\\"
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: swc_utils
3
+ Version: 0.0.1
4
+ Summary: Provides utility functions for SWC projects
5
+ Author-email: Davis_Software <davissoftware6@gmail.com>
6
+ Project-URL: Homepage, https://projects.software-city.org/
7
+ Project-URL: Issues, https://projects.software-city.org/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: Flask==3.0.3
15
+ Requires-Dist: Flask-SQLAlchemy==3.1.1
16
+
17
+ ### SWC Utils
18
+
19
+ This repository contains a collection of utilities for SWC projects.
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/swc_utils/__init__.py
5
+ src/swc_utils.egg-info/PKG-INFO
6
+ src/swc_utils.egg-info/SOURCES.txt
7
+ src/swc_utils.egg-info/dependency_links.txt
8
+ src/swc_utils.egg-info/requires.txt
9
+ src/swc_utils.egg-info/top_level.txt
10
+ src/swc_utils/database/__init__.py
11
+ src/swc_utils/database/connection_profile.py
12
+ src/swc_utils/database/database_connection.py
13
+ src/swc_utils/other/__init__.py
14
+ src/swc_utils/other/generator_utils.py
15
+ src/swc_utils/tools/__init__.py
16
+ src/swc_utils/tools/config.py
17
+ src/swc_utils/tools/route_loader.py
18
+ src/swc_utils/web/__init__.py
19
+ src/swc_utils/web/adv_responses.py
20
+ src/swc_utils/web/auth_manager.py
21
+ src/swc_utils/web/request_codes.py
22
+ src/swc_utils/wsl/__init__.py
23
+ src/swc_utils/wsl/wsl_compatability.py
@@ -0,0 +1,2 @@
1
+ Flask==3.0.3
2
+ Flask-SQLAlchemy==3.1.1
@@ -0,0 +1 @@
1
+ swc_utils