Flask-Super 0.1.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.
@@ -0,0 +1,16 @@
1
+ Apache Software License 2.0
2
+
3
+ Copyright (c) 2023, Abilian SAS
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.1
2
+ Name: Flask-Super
3
+ Version: 0.1.0
4
+ Summary: Patterns and idioms for Flask applications.
5
+ Home-page: https://github.com/abilian/flask_plus
6
+ Author: Abilian SAS
7
+ Author-email: sf@abilian.com
8
+ Requires-Python: >=3.10,<4
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: flask (>=3.0.0,<4.0.0)
16
+ Requires-Dist: svcs (>=23.21.0,<24.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Flask-Plus
20
+
21
+ [![image](https://img.shields.io/pypi/v/flask_plus.svg)](https://pypi.python.org/pypi/flask_plus)
22
+
23
+ [![Documentation Status](https://readthedocs.org/projects/flask-plus/badge/?version=latest)](https://flask-plus.readthedocs.io/en/latest/?version=latest)
24
+
25
+
26
+ ## Flask patterns and idoms
27
+
28
+ - Free software: Apache Software License 2.0
29
+ - Documentation: <https://flask-plus.readthedocs.io>.
30
+
31
+
32
+ ## Features
33
+
34
+ - Decorator-based registration system for services (using [svcs](https://svcs.hynek.me/en/stable/))
35
+ - Powerful inspection CLI command.
36
+
37
+
38
+ ## Status
39
+
40
+ This is a preview. Expect the API to change.
41
+
42
+
43
+ ## Credits
44
+
45
+ This package was created with [Cruft](https://cruft.github.io/cruft/)
46
+ and the
47
+ [abilian/cookiecutter-abilian-python](https://github.com/abilian/cookiecutter-abilian-python)
48
+ project template.
49
+
@@ -0,0 +1,30 @@
1
+ # Flask-Plus
2
+
3
+ [![image](https://img.shields.io/pypi/v/flask_plus.svg)](https://pypi.python.org/pypi/flask_plus)
4
+
5
+ [![Documentation Status](https://readthedocs.org/projects/flask-plus/badge/?version=latest)](https://flask-plus.readthedocs.io/en/latest/?version=latest)
6
+
7
+
8
+ ## Flask patterns and idoms
9
+
10
+ - Free software: Apache Software License 2.0
11
+ - Documentation: <https://flask-plus.readthedocs.io>.
12
+
13
+
14
+ ## Features
15
+
16
+ - Decorator-based registration system for services (using [svcs](https://svcs.hynek.me/en/stable/))
17
+ - Powerful inspection CLI command.
18
+
19
+
20
+ ## Status
21
+
22
+ This is a preview. Expect the API to change.
23
+
24
+
25
+ ## Credits
26
+
27
+ This package was created with [Cruft](https://cruft.github.io/cruft/)
28
+ and the
29
+ [abilian/cookiecutter-abilian-python](https://github.com/abilian/cookiecutter-abilian-python)
30
+ project template.
@@ -0,0 +1,176 @@
1
+ [tool.poetry]
2
+ name = "Flask-Super"
3
+ version = "0.1.0"
4
+ homepage = "https://github.com/abilian/flask_plus"
5
+ description = "Patterns and idioms for Flask applications."
6
+ authors = ["Abilian SAS <sf@abilian.com>"]
7
+ readme = "README.md"
8
+ classifiers = [
9
+ 'Development Status :: 2 - Pre-Alpha',
10
+ 'Intended Audience :: Developers',
11
+ 'Programming Language :: Python :: 3',
12
+ 'Programming Language :: Python :: 3.10',
13
+ 'Programming Language :: Python :: 3.11',
14
+ 'Programming Language :: Python :: 3.12',
15
+ ]
16
+ packages = [
17
+ { include = "flask_plus", from = "src" },
18
+ { include = "tests", format = "sdist" },
19
+ ]
20
+
21
+
22
+ [tool.poetry.dependencies]
23
+ # We're uing pattern matching, so we need Python >=3.10
24
+ python = ">=3.10,<4"
25
+
26
+ flask = "^3.0.0"
27
+ svcs = "^23.21.0"
28
+
29
+
30
+ [tool.poetry.group.dev.dependencies]
31
+ ## Standard cruft
32
+ abilian-devtools = "*"
33
+
34
+ # Cruft (project templates management)
35
+ cruft = "*"
36
+ toml = "*"
37
+
38
+ ## /standard cruft
39
+
40
+ [build-system]
41
+ requires = ["poetry-core>=1.0.0"]
42
+ build-backend = "poetry.core.masonry.api"
43
+
44
+ # ---
45
+
46
+ [tool.isort]
47
+ profile = "black"
48
+
49
+ # ---
50
+
51
+ # pyproject.toml
52
+ [tool.pytest.ini_options]
53
+ filterwarnings = [
54
+ # 'ignore:.*contextfunction.*:DeprecationWarning',
55
+ # 'ignore:.*Unmanaged.*:sqlalchemy.exc.SAWarning'
56
+ ]
57
+ addopts = "--tb=short"
58
+ testpaths = [
59
+ "tests",
60
+ "src",
61
+ ]
62
+
63
+ # ---
64
+
65
+ [tool.ruff]
66
+ #select = [
67
+ # "F",
68
+ # "E",
69
+ # "C90",
70
+ # "I",
71
+ # "UP",
72
+ # "N",
73
+ # "YTT",
74
+ # "B",
75
+ # "A",
76
+ # "C4",
77
+ # "ICN",
78
+ # "Q",
79
+ # "S",
80
+ # "BLE",
81
+ # "RET",
82
+ # "SIM",
83
+ # "TID",
84
+ # "RUF",
85
+ # "PLC", "PLE", "PLR", "PLW",
86
+ #]
87
+ ## Add later: "ANN", "ERA"...
88
+
89
+ ignore = [
90
+ "S101", # Use of `assert` detected
91
+ "I001", # Import block is un-sorted or un-formatted (WHY!?)
92
+ "PLR0913", # Too many arguments in function definition
93
+ "RET505", # Unnecessary `else` after `return` statement
94
+ "RET504", # Unnecessary assignment before `return` statement
95
+ ]
96
+
97
+ # ---
98
+
99
+ [tool.bandit]
100
+ skips = [
101
+ "B404", # blacklist
102
+ "B603", # subprocess_without_shell_equals_true
103
+ ]
104
+
105
+ # ---
106
+
107
+ [tool.pyanalyze]
108
+ paths = ["src/"]
109
+ import_paths = ["."]
110
+
111
+ # Additional checks
112
+ bare_ignore = true
113
+ missing_f = true
114
+ use_fstrings = true
115
+ value_always_true = true
116
+
117
+ # TODO: fix issues and activate
118
+ #unused_ignore = true
119
+ #enforce_no_unused = true
120
+ #incompatible_override = true
121
+ #missing_parameter_annotation = true
122
+ #missing_return_annotation = true
123
+ #suggested_parameter_type = true
124
+ #suggested_return_type = true
125
+ #use_fstrings = true
126
+ #value_always_true = true
127
+
128
+ # TODO: fix issues and remove
129
+ attribute_is_never_set = false
130
+ duplicate_dict_key = false
131
+ import_failed = false
132
+ impossible_pattern = false
133
+ incompatible_argument = false
134
+ incompatible_call = false
135
+ incompatible_return_value = false
136
+ internal_error = false
137
+ missing_return = false
138
+ possibly_undefined_name = false
139
+ undefined_attribute = false
140
+ unused_variable = false
141
+
142
+ # ---
143
+
144
+ [tool.deptry]
145
+ ignore_obsolete = [
146
+ ]
147
+ ignore_missing = [
148
+ ]
149
+ ignore_transitive = [
150
+ ]
151
+ exclude = [
152
+ '.tox', 'tests', 'sandbox', 'doc', 'scripts',
153
+ ]
154
+
155
+
156
+ # ---
157
+
158
+ [tool.pyright]
159
+ exclude = [
160
+ '.tox',
161
+ '.nox',
162
+ 'tests',
163
+ 'sandbox',
164
+ 'doc',
165
+ 'scripts',
166
+ 'tmp',
167
+ ]
168
+ include = ["src"]
169
+
170
+ # pyright has issues with modules imported from a root __init__.py
171
+ reportPrivateImportUsage = false
172
+
173
+ # Temp
174
+ reportGeneralTypeIssues = false
175
+ reportMissingImports = false
176
+ reportOptionalSubscript = false
@@ -0,0 +1 @@
1
+ """Top-level package for Flask-Plus."""
@@ -0,0 +1,36 @@
1
+ import click
2
+
3
+ from flask_plus.registry import lookup, register
4
+
5
+ __all__ = ["register_commands", "command", "group"]
6
+
7
+ from flask_plus.scanner import scan_package
8
+
9
+
10
+ def command(*args, **kwargs):
11
+ def decorator(func):
12
+ module = func.__module__
13
+ name = func.__name__
14
+ cmd = click.command(*args, **kwargs)(func)
15
+ register(cmd, name=name, module=module, tag="cli")
16
+ return cmd
17
+
18
+ return decorator
19
+
20
+
21
+ def group(*args, **kwargs):
22
+ def decorator(func):
23
+ module = func.__module__
24
+ name = func.__name__
25
+ cmd = click.group(*args, **kwargs)(func)
26
+ register(cmd, name=name, module=module, tags="cli")
27
+ return cmd
28
+
29
+ return decorator
30
+
31
+
32
+ def register_commands(app):
33
+ scan_package("flask_plus.cli.commands")
34
+
35
+ for obj in lookup(click.Command):
36
+ app.cli.add_command(obj)
@@ -0,0 +1,71 @@
1
+ from cleez.colors import blue
2
+ from flask.cli import with_appcontext
3
+ from svcs.flask import container
4
+
5
+ from flask_plus.cli import command
6
+ from flask_plus.registry import registry
7
+
8
+
9
+ @command(short_help="Inspect app")
10
+ @with_appcontext
11
+ def inspect():
12
+ inspect_registry()
13
+ inspect_services()
14
+
15
+
16
+ def inspect_registry():
17
+ print(blue("\nRegistry:"))
18
+ print()
19
+
20
+ def sorter(t):
21
+ _, metadata = t
22
+ return metadata.tag, metadata.name
23
+
24
+ objs = sorted(registry.items(), key=sorter)
25
+
26
+ rows = []
27
+ for obj, metadata in objs:
28
+ name = metadata.name
29
+ module = metadata.module
30
+ tag = metadata.tag
31
+ obj_type = str(type(obj))
32
+ rows.append((name, obj_type, tag, module))
33
+
34
+ headers = ["Obj", "Type", "Tag", "Module"]
35
+ print_table(headers, rows)
36
+
37
+
38
+ def inspect_services():
39
+ print(blue("\nServices:"))
40
+ print()
41
+
42
+ registry = container.registry
43
+ services = []
44
+ for registered_service in registry._services.values():
45
+ services.append(
46
+ (registered_service.svc_type.__name__, registered_service.factory)
47
+ )
48
+ services.sort(key=lambda x: x[0].lower())
49
+
50
+ rows = []
51
+ for k, v in services:
52
+ if hasattr(v, "cls"):
53
+ v = v.cls # noqa: PLW2901
54
+
55
+ name = v.__name__
56
+ module = v.__module__
57
+ rows.append((k, name, module))
58
+
59
+ headers = ["Type", "Factory", "Module"]
60
+ print_table(headers, rows)
61
+
62
+
63
+ def print_table(headers, rows):
64
+ rows.insert(0, headers)
65
+ widths = [max(len(row[i]) for row in rows) for i in range(len(headers))]
66
+ rows.insert(1, ["-" * w for w in widths])
67
+ template = " ".join(f"{{{i}:<{w}}}" for i, w in enumerate(widths))
68
+
69
+ for row in rows:
70
+ print(template.format(*row))
71
+ print()
@@ -0,0 +1,12 @@
1
+ from .cli import command, group
2
+ from .registry import register
3
+
4
+ __all__ = ["register", "command", "group", "service"]
5
+
6
+
7
+ def service(obj):
8
+ return register(obj, tag="service")
9
+
10
+
11
+ def singleton(obj):
12
+ return register(obj, tag="singleton")
@@ -0,0 +1,84 @@
1
+ from typing import Any
2
+
3
+ from attr import define, field
4
+
5
+ __all__ = ["registry", "register", "lookup"]
6
+
7
+
8
+ @define
9
+ class Metadata:
10
+ name: str = ""
11
+ module: str = ""
12
+ tag: str = ""
13
+ extras: dict[str, Any] = field(factory=dict)
14
+
15
+
16
+ @define
17
+ class Registry:
18
+ registered: dict[Any, Metadata] = field(factory=dict)
19
+
20
+ def register(self, obj, name="", module="", tag="", extras=None):
21
+ if not name:
22
+ name = obj.__name__
23
+ if not module:
24
+ module = obj.__module__
25
+ if extras is None:
26
+ extras = {}
27
+
28
+ metadata = Metadata(name=name, module=module, tag=tag, extras=extras)
29
+ self.registered[obj] = metadata
30
+ return obj
31
+
32
+ def lookup(self, key: str | type = "", tag: str = "") -> list:
33
+ match key:
34
+ case "":
35
+ objs = list(self.registered.items())
36
+ case str():
37
+ objs = self._lookup_by_name(key)
38
+ case type():
39
+ objs = self._lookup_by_type(key)
40
+ case _:
41
+ raise TypeError(f"Invalid key type: {type(key)}")
42
+
43
+ if tag:
44
+ return [obj for obj, metadata in objs if tag == metadata.tag]
45
+ else:
46
+ return [obj for obj, _metadata in objs]
47
+
48
+ def _lookup_by_name(self, name: str) -> list[tuple[Any, Metadata]]:
49
+ result = []
50
+ for obj, metadata in self.registered.items():
51
+ if metadata.name == name:
52
+ result.append((obj, metadata))
53
+ return result
54
+
55
+ def _lookup_by_type(self, cls: type) -> list[tuple[Any, Metadata]]:
56
+ result: list[tuple[Any, Metadata]] = []
57
+ for obj, metadata in self.registered.items():
58
+ if isinstance(obj, type):
59
+ if issubclass(obj, cls):
60
+ result.append((obj, metadata))
61
+ elif isinstance(obj, cls):
62
+ result.append((obj, metadata))
63
+
64
+ return result
65
+
66
+ def __iter__(self):
67
+ return iter(self.registered)
68
+
69
+ def items(self):
70
+ return self.registered.items()
71
+
72
+ def __contains__(self, obj):
73
+ return obj in self.registered
74
+
75
+ def get_metadata(self, obj: Any) -> Metadata:
76
+ return self.registered[obj]
77
+
78
+ def clear(self):
79
+ self.registered.clear()
80
+
81
+
82
+ registry = Registry()
83
+ register = registry.register
84
+ lookup = registry.lookup
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import pkgutil
5
+ from collections.abc import Iterator
6
+
7
+
8
+ def scan_packages(package_names: Iterator[str]):
9
+ """Scan all packages from the given list."""
10
+ for package_name in package_names:
11
+ scan_package(package_name)
12
+
13
+
14
+ def scan_package(package_name: str):
15
+ """Import all modules in a package (recursively), for side effects."""
16
+ for module_name in _iter_module_names(package_name):
17
+ importlib.import_module(module_name)
18
+
19
+
20
+ def _iter_module_names(package_name: str):
21
+ package_or_module = importlib.import_module(package_name)
22
+ if not hasattr(package_or_module, "__path__"):
23
+ # module, not package
24
+ return
25
+
26
+ path = package_or_module.__path__
27
+ prefix = package_or_module.__name__ + "."
28
+ for _, module_name, _ in pkgutil.walk_packages(path, prefix):
29
+ yield module_name
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from inspect import signature
5
+ from typing import Any
6
+
7
+ import svcs
8
+ from attr import define, field
9
+ from flask import Flask
10
+ from svcs.flask import register_factory
11
+
12
+ __all__ = [
13
+ "register_services",
14
+ ]
15
+
16
+ from flask_plus.registry import lookup
17
+
18
+
19
+ def register_services(app: Flask):
20
+ services = lookup(tag="service")
21
+
22
+ for cls_or_factory in services:
23
+ if factory := getattr(cls_or_factory, "svcs_factory", None):
24
+ register_factory(app, cls_or_factory, factory)
25
+
26
+ elif isinstance(cls_or_factory, type):
27
+ cls = cls_or_factory
28
+ svcs.flask.register_factory(app, cls, cls)
29
+
30
+ else:
31
+ factory = cls_or_factory
32
+ sig = signature(factory)
33
+ cls_name = sig.return_annotation
34
+ module = importlib.import_module(factory.__module__)
35
+ cls = getattr(module, cls_name)
36
+ svcs.flask.register_factory(app, cls, factory)
37
+
38
+
39
+ @define
40
+ class SingletonFactory:
41
+ cls: type
42
+ holder: list[Any] = field(factory=list)
43
+
44
+ def __call__(self) -> Any:
45
+ if not self.holder:
46
+ self.holder.append(self.cls())
47
+ return self.holder[0]
48
+
49
+
50
+ def register_singletons(app: Flask):
51
+ singletons = lookup(tag="singleton")
52
+
53
+ for cls in singletons:
54
+ svcs.flask.register_factory(app, cls, SingletonFactory(cls))
@@ -0,0 +1 @@
1
+ """Unit test package for flask_plus."""
@@ -0,0 +1,32 @@
1
+ import pytest
2
+ import svcs
3
+ from click.testing import CliRunner
4
+ from flask import Flask
5
+
6
+ from flask_plus.decorators import service
7
+ from flask_plus.scanner import scan_package
8
+ from flask_plus.services import register_services
9
+
10
+
11
+ @service
12
+ class ServiceClass:
13
+ pass
14
+
15
+
16
+ def create_app() -> Flask:
17
+ app = Flask(__name__)
18
+ app = svcs.flask.init_app(app)
19
+
20
+ return app
21
+
22
+
23
+ def test_cli():
24
+ scan_package("flask_plus.cli.commands")
25
+
26
+ app = create_app()
27
+ register_services(app)
28
+
29
+ runner = CliRunner()
30
+ result = runner.invoke(app.cli, ["inspect"])
31
+ print(result.output)
32
+ assert result.exit_code == 0
@@ -0,0 +1,55 @@
1
+ import svcs
2
+ from flask import Flask
3
+ from svcs.flask import container
4
+
5
+ from flask_plus.decorators import service, singleton
6
+ from flask_plus.services import register_services, register_singletons
7
+
8
+
9
+ def create_app() -> Flask:
10
+ app = Flask(__name__)
11
+ app = svcs.flask.init_app(app)
12
+ return app
13
+
14
+
15
+ def test_single_service():
16
+ @service
17
+ class ServiceClass:
18
+ pass
19
+
20
+ app = create_app()
21
+ register_services(app)
22
+
23
+ with app.app_context():
24
+ svc = container.get(ServiceClass)
25
+ assert svc is not None
26
+ assert isinstance(svc, ServiceClass)
27
+
28
+ # The service is unique over a single request.
29
+ svc2 = container.get(ServiceClass)
30
+ assert svc2 == svc
31
+
32
+ with app.app_context():
33
+ svc3 = container.get(ServiceClass)
34
+ assert svc3 != svc
35
+
36
+
37
+ def test_singleton():
38
+ """Test that a singleton service is only created once over the lifetime
39
+ of an application."""
40
+
41
+ @singleton
42
+ class Singleton:
43
+ pass
44
+
45
+ app = create_app()
46
+ register_singletons(app)
47
+
48
+ with app.app_context():
49
+ svc1 = container.get(Singleton)
50
+ svc2 = container.get(Singleton)
51
+ assert svc1 is svc2
52
+
53
+ with app.app_context():
54
+ svc3 = container.get(Singleton)
55
+ assert svc3 == svc1