bisslog-flask 0.0.1__tar.gz → 0.0.3__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.
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/PKG-INFO +59 -44
- bisslog_flask-0.0.3/README.md +133 -0
- bisslog_flask-0.0.3/bisslog_flask/builder/builder_flask_app_manager.py +371 -0
- bisslog_flask-0.0.3/bisslog_flask/builder/static_python_construct_data.py +172 -0
- bisslog_flask-0.0.3/bisslog_flask/cli/__init__.py +90 -0
- bisslog_flask-0.0.3/bisslog_flask/cli/commands/build.py +57 -0
- bisslog_flask-0.0.3/bisslog_flask/cli/commands/run.py +52 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/initializer/bisslog_flask_http_resolver.py +53 -12
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/initializer/bisslog_flask_resolver.py +0 -1
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/initializer/bisslog_flask_ws_resolver.py +25 -9
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/initializer/init_flask_app_manager.py +16 -2
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/socket_helper/socket_helper.py +0 -3
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask.egg-info/PKG-INFO +59 -44
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask.egg-info/SOURCES.txt +19 -1
- bisslog_flask-0.0.3/bisslog_flask.egg-info/entry_points.txt +2 -0
- bisslog_flask-0.0.3/bisslog_flask.egg-info/requires.txt +12 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/pylintrc +4 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/pyproject.toml +6 -2
- bisslog_flask-0.0.3/requirements/requirements-async.txt +1 -0
- bisslog_flask-0.0.3/requirements.txt +3 -0
- bisslog_flask-0.0.3/tests/__init__.py +0 -0
- bisslog_flask-0.0.3/tests/unit/__init__.py +0 -0
- bisslog_flask-0.0.3/tests/unit/builder/__init__.py +0 -0
- bisslog_flask-0.0.3/tests/unit/builder/test_builder_flask_app_manager.py +105 -0
- bisslog_flask-0.0.3/tests/unit/builder/test_builder_full.py +64 -0
- bisslog_flask-0.0.3/tests/unit/builder/test_static_python_res.py +72 -0
- bisslog_flask-0.0.3/tests/unit/cli/__init__.py +0 -0
- bisslog_flask-0.0.3/tests/unit/cli/test_build.py +29 -0
- bisslog_flask-0.0.3/tests/unit/cli/test_cli.py +72 -0
- bisslog_flask-0.0.3/tests/unit/cli/test_run.py +31 -0
- bisslog_flask-0.0.3/tests/unit/test_http_resolver.py +268 -0
- bisslog_flask-0.0.3/tests/unit/test_http_resolver_lambda_fn.py +93 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/tests/unit/test_init_app_manager.py +36 -12
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/tests/unit/test_ws_resolver.py +4 -3
- bisslog_flask-0.0.1/README.md +0 -120
- bisslog_flask-0.0.1/bisslog_flask.egg-info/requires.txt +0 -9
- bisslog_flask-0.0.1/requirements.txt +0 -3
- bisslog_flask-0.0.1/tests/unit/test_http_resolver.py +0 -97
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/.github/workflows/publish-pypi.yml +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/.github/workflows/publish-test-pypi.yml +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/.github/workflows/receive-changes.yml +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/.gitignore +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/LICENSE +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask/__init__.py +0 -0
- {bisslog_flask-0.0.1/bisslog_flask/initializer → bisslog_flask-0.0.3/bisslog_flask/builder}/__init__.py +0 -0
- {bisslog_flask-0.0.1/bisslog_flask/socket_helper → bisslog_flask-0.0.3/bisslog_flask/cli/commands}/__init__.py +0 -0
- {bisslog_flask-0.0.1/tests → bisslog_flask-0.0.3/bisslog_flask/initializer}/__init__.py +0 -0
- {bisslog_flask-0.0.1/tests/unit → bisslog_flask-0.0.3/bisslog_flask/socket_helper}/__init__.py +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask.egg-info/dependency_links.txt +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/bisslog_flask.egg-info/top_level.txt +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/requirements/requirements-flask-optional.txt +0 -0
- {bisslog_flask-0.0.1 → bisslog_flask-0.0.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: bisslog_flask
|
3
|
-
Version: 0.0.
|
3
|
+
Version: 0.0.3
|
4
4
|
Summary: It is an extension of the bisslog library to support processes with flask
|
5
5
|
Author-email: Darwin Stiven Herrera Cartagena <darwinsherrerac@gmail.com>
|
6
6
|
Project-URL: Homepage, https://github.com/darwinhc/bisslog-flask
|
@@ -10,54 +10,54 @@ Classifier: Operating System :: OS Independent
|
|
10
10
|
Requires-Python: >=3.7
|
11
11
|
Description-Content-Type: text/markdown
|
12
12
|
License-File: LICENSE
|
13
|
-
Requires-Dist: bisslog>=0.0.
|
14
|
-
Requires-Dist: bisslog-schema>=0.0.
|
13
|
+
Requires-Dist: bisslog>=0.0.9
|
14
|
+
Requires-Dist: bisslog-schema>=0.0.10
|
15
15
|
Requires-Dist: flask
|
16
16
|
Provides-Extra: websocket
|
17
17
|
Requires-Dist: flask-socketio; extra == "websocket"
|
18
18
|
Provides-Extra: cors
|
19
19
|
Requires-Dist: flask-cors>=6.0.0; extra == "cors"
|
20
|
+
Provides-Extra: async
|
21
|
+
Requires-Dist: Flask[async]>=2.2; extra == "async"
|
20
22
|
Dynamic: license-file
|
21
23
|
|
22
|
-
|
23
24
|
# bisslog-flask
|
24
25
|
|
25
26
|
[](https://pypi.org/project/bisslog-flask/)
|
26
27
|
[](LICENSE)
|
27
28
|
|
28
|
-
**bisslog-flask** is an extension of the
|
29
|
+
**bisslog-flask** is an extension of the Bisslog library to support processes with Flask.
|
30
|
+
It enables dynamic HTTP and WebSocket route registration from use case metadata, allowing developers to build clean, modular, and metadata-driven APIs with minimal boilerplate.
|
29
31
|
|
30
|
-
Part of the
|
32
|
+
Part of the Bisslog ecosystem, it is designed to work seamlessly with domain-centric architectures like Hexagonal or Clean Architecture.
|
31
33
|
|
32
|
-
|
34
|
+
---
|
33
35
|
|
34
|
-
|
36
|
+
## ✨ Features
|
35
37
|
|
38
|
+
- 🔁 Dynamic route registration for HTTP and WebSocket triggers
|
36
39
|
- 🧠 Metadata-driven setup – use YAML or JSON to declare your use cases
|
37
|
-
|
38
|
-
- 🔒 Automatic CORS per endpoint using flask-cors
|
39
|
-
|
40
|
+
- 🔒 Automatic CORS per endpoint using `flask-cors`
|
40
41
|
- 🔌 Extensible resolver pattern – plug in your own processor
|
41
|
-
|
42
42
|
- ⚙️ Mapper integration – maps HTTP request parts to domain function arguments
|
43
43
|
|
44
|
-
|
44
|
+
---
|
45
45
|
|
46
46
|
## 📦 Installation
|
47
47
|
|
48
|
-
|
48
|
+
```bash
|
49
49
|
pip install bisslog-flask
|
50
|
-
|
51
|
-
|
52
|
-
|
50
|
+
```
|
53
51
|
|
52
|
+
---
|
54
53
|
|
55
54
|
## 🚀 Quickstart
|
56
55
|
|
57
56
|
### Programmatically
|
58
57
|
|
59
|
-
if you want to configure the app before
|
60
|
-
|
58
|
+
Use this approach if you want to configure the app before Bisslog touches it:
|
59
|
+
|
60
|
+
```python
|
61
61
|
from flask import Flask
|
62
62
|
from bisslog_flask import BisslogFlask
|
63
63
|
|
@@ -70,11 +70,11 @@ BisslogFlask(
|
|
70
70
|
|
71
71
|
if __name__ == "__main__":
|
72
72
|
app.run(debug=True)
|
73
|
-
|
73
|
+
```
|
74
74
|
|
75
|
-
|
75
|
+
Or use the factory version:
|
76
76
|
|
77
|
-
|
77
|
+
```python
|
78
78
|
from bisslog_flask import BisslogFlask
|
79
79
|
|
80
80
|
app = BisslogFlask(
|
@@ -84,58 +84,73 @@ app = BisslogFlask(
|
|
84
84
|
|
85
85
|
if __name__ == "__main__":
|
86
86
|
app.run(debug=True)
|
87
|
-
|
88
|
-
|
87
|
+
```
|
89
88
|
|
89
|
+
---
|
90
90
|
|
91
|
-
##
|
91
|
+
## 🖥️ CLI Usage
|
92
92
|
|
93
|
-
|
93
|
+
You can also use the `bisslog_flask` CLI to run or generate a Flask app.
|
94
94
|
|
95
|
+
```bash
|
96
|
+
bisslog_flask run [--metadata-file FILE] [--use-cases-folder-path DIR]
|
97
|
+
[--infra-folder-path DIR] [--encoding ENC]
|
98
|
+
[--secret-key KEY] [--jwt-secret-key KEY]
|
95
99
|
|
96
|
-
|
100
|
+
bisslog_flask build [--metadata-file FILE] [--use-cases-folder-path DIR]
|
101
|
+
[--infra-folder-path DIR] [--encoding ENC]
|
102
|
+
[--target-filename FILE]
|
103
|
+
```
|
97
104
|
|
98
|
-
|
105
|
+
- `run`: Launches the Flask application from metadata.
|
106
|
+
- `build`: Generates a boilerplate Flask file (`flask_app.py` by default).
|
99
107
|
|
100
|
-
|
108
|
+
All options are optional. You can override defaults via CLI flags.
|
101
109
|
|
102
|
-
|
110
|
+
---
|
103
111
|
|
112
|
+
## 🔐 CORS Handling
|
104
113
|
|
105
|
-
|
114
|
+
CORS is applied only when `allow_cors: true` is specified in the trigger.
|
106
115
|
|
107
|
-
|
116
|
+
Fully dynamic: works even with Flask dynamic routes like `/users/<id>`.
|
108
117
|
|
109
|
-
|
118
|
+
Powered by `@cross_origin` from `flask-cors`.
|
110
119
|
|
111
|
-
|
120
|
+
---
|
112
121
|
|
113
|
-
|
122
|
+
## ✅ Requirements
|
114
123
|
|
115
|
-
|
124
|
+
- Python ≥ 3.7
|
125
|
+
- Flask ≥ 2.0
|
126
|
+
- bisslog-schema ≥ 0.0.3
|
127
|
+
- flask-cors
|
128
|
+
- (Optional) flask-sock if using WebSocket triggers
|
116
129
|
|
130
|
+
---
|
117
131
|
|
118
132
|
## 🧪 Testing Tip
|
119
133
|
|
120
|
-
You can test the generated Flask app directly with `app.test_client()` if
|
134
|
+
You can test the generated Flask app directly with `app.test_client()` if using the programmatic interface:
|
121
135
|
|
122
136
|
```python
|
123
137
|
from bisslog_flask import BisslogFlask
|
124
138
|
|
125
139
|
def test_user_create():
|
126
|
-
app = BisslogFlask(
|
140
|
+
app = BisslogFlask(
|
141
|
+
metadata_file="metadata.yml",
|
142
|
+
use_cases_folder_path="src/use_cases"
|
143
|
+
)
|
127
144
|
client = app.test_client()
|
128
145
|
response = client.post("/user", json={"name": "Ana", "email": "ana@example.com"})
|
129
146
|
assert response.status_code == 200
|
130
147
|
```
|
131
148
|
|
132
|
-
|
133
|
-
|
149
|
+
If you're generating the code (boilerplate), you just need to test your use cases.
|
134
150
|
|
151
|
+
---
|
135
152
|
|
136
153
|
## 📜 License
|
137
154
|
|
138
|
-
This project is licensed under the MIT License.
|
139
|
-
|
140
|
-
|
141
|
-
|
155
|
+
This project is licensed under the MIT License.
|
156
|
+
See the [LICENSE](LICENSE) file for details.
|
@@ -0,0 +1,133 @@
|
|
1
|
+
# bisslog-flask
|
2
|
+
|
3
|
+
[](https://pypi.org/project/bisslog-flask/)
|
4
|
+
[](LICENSE)
|
5
|
+
|
6
|
+
**bisslog-flask** is an extension of the Bisslog library to support processes with Flask.
|
7
|
+
It enables dynamic HTTP and WebSocket route registration from use case metadata, allowing developers to build clean, modular, and metadata-driven APIs with minimal boilerplate.
|
8
|
+
|
9
|
+
Part of the Bisslog ecosystem, it is designed to work seamlessly with domain-centric architectures like Hexagonal or Clean Architecture.
|
10
|
+
|
11
|
+
---
|
12
|
+
|
13
|
+
## ✨ Features
|
14
|
+
|
15
|
+
- 🔁 Dynamic route registration for HTTP and WebSocket triggers
|
16
|
+
- 🧠 Metadata-driven setup – use YAML or JSON to declare your use cases
|
17
|
+
- 🔒 Automatic CORS per endpoint using `flask-cors`
|
18
|
+
- 🔌 Extensible resolver pattern – plug in your own processor
|
19
|
+
- ⚙️ Mapper integration – maps HTTP request parts to domain function arguments
|
20
|
+
|
21
|
+
---
|
22
|
+
|
23
|
+
## 📦 Installation
|
24
|
+
|
25
|
+
```bash
|
26
|
+
pip install bisslog-flask
|
27
|
+
```
|
28
|
+
|
29
|
+
---
|
30
|
+
|
31
|
+
## 🚀 Quickstart
|
32
|
+
|
33
|
+
### Programmatically
|
34
|
+
|
35
|
+
Use this approach if you want to configure the app before Bisslog touches it:
|
36
|
+
|
37
|
+
```python
|
38
|
+
from flask import Flask
|
39
|
+
from bisslog_flask import BisslogFlask
|
40
|
+
|
41
|
+
app = Flask(__name__)
|
42
|
+
BisslogFlask(
|
43
|
+
metadata_file="metadata.yml",
|
44
|
+
use_cases_folder_path="src/domain/use_cases",
|
45
|
+
app=app
|
46
|
+
)
|
47
|
+
|
48
|
+
if __name__ == "__main__":
|
49
|
+
app.run(debug=True)
|
50
|
+
```
|
51
|
+
|
52
|
+
Or use the factory version:
|
53
|
+
|
54
|
+
```python
|
55
|
+
from bisslog_flask import BisslogFlask
|
56
|
+
|
57
|
+
app = BisslogFlask(
|
58
|
+
metadata_file="metadata.yml",
|
59
|
+
use_cases_folder_path="src/domain/use_cases"
|
60
|
+
)
|
61
|
+
|
62
|
+
if __name__ == "__main__":
|
63
|
+
app.run(debug=True)
|
64
|
+
```
|
65
|
+
|
66
|
+
---
|
67
|
+
|
68
|
+
## 🖥️ CLI Usage
|
69
|
+
|
70
|
+
You can also use the `bisslog_flask` CLI to run or generate a Flask app.
|
71
|
+
|
72
|
+
```bash
|
73
|
+
bisslog_flask run [--metadata-file FILE] [--use-cases-folder-path DIR]
|
74
|
+
[--infra-folder-path DIR] [--encoding ENC]
|
75
|
+
[--secret-key KEY] [--jwt-secret-key KEY]
|
76
|
+
|
77
|
+
bisslog_flask build [--metadata-file FILE] [--use-cases-folder-path DIR]
|
78
|
+
[--infra-folder-path DIR] [--encoding ENC]
|
79
|
+
[--target-filename FILE]
|
80
|
+
```
|
81
|
+
|
82
|
+
- `run`: Launches the Flask application from metadata.
|
83
|
+
- `build`: Generates a boilerplate Flask file (`flask_app.py` by default).
|
84
|
+
|
85
|
+
All options are optional. You can override defaults via CLI flags.
|
86
|
+
|
87
|
+
---
|
88
|
+
|
89
|
+
## 🔐 CORS Handling
|
90
|
+
|
91
|
+
CORS is applied only when `allow_cors: true` is specified in the trigger.
|
92
|
+
|
93
|
+
Fully dynamic: works even with Flask dynamic routes like `/users/<id>`.
|
94
|
+
|
95
|
+
Powered by `@cross_origin` from `flask-cors`.
|
96
|
+
|
97
|
+
---
|
98
|
+
|
99
|
+
## ✅ Requirements
|
100
|
+
|
101
|
+
- Python ≥ 3.7
|
102
|
+
- Flask ≥ 2.0
|
103
|
+
- bisslog-schema ≥ 0.0.3
|
104
|
+
- flask-cors
|
105
|
+
- (Optional) flask-sock if using WebSocket triggers
|
106
|
+
|
107
|
+
---
|
108
|
+
|
109
|
+
## 🧪 Testing Tip
|
110
|
+
|
111
|
+
You can test the generated Flask app directly with `app.test_client()` if using the programmatic interface:
|
112
|
+
|
113
|
+
```python
|
114
|
+
from bisslog_flask import BisslogFlask
|
115
|
+
|
116
|
+
def test_user_create():
|
117
|
+
app = BisslogFlask(
|
118
|
+
metadata_file="metadata.yml",
|
119
|
+
use_cases_folder_path="src/use_cases"
|
120
|
+
)
|
121
|
+
client = app.test_client()
|
122
|
+
response = client.post("/user", json={"name": "Ana", "email": "ana@example.com"})
|
123
|
+
assert response.status_code == 200
|
124
|
+
```
|
125
|
+
|
126
|
+
If you're generating the code (boilerplate), you just need to test your use cases.
|
127
|
+
|
128
|
+
---
|
129
|
+
|
130
|
+
## 📜 License
|
131
|
+
|
132
|
+
This project is licensed under the MIT License.
|
133
|
+
See the [LICENSE](LICENSE) file for details.
|
@@ -0,0 +1,371 @@
|
|
1
|
+
"""
|
2
|
+
Module for generating a Flask application boilerplate from Bisslog metadata and use case code.
|
3
|
+
|
4
|
+
This builder analyzes declared metadata (e.g., triggers) and discovered use case implementations,
|
5
|
+
and generates the corresponding Flask code—including HTTP routes, WebSocket endpoints, security
|
6
|
+
configuration, and runtime setup.
|
7
|
+
|
8
|
+
The generated code is returned as a full Python script and can be written to a file (e.g.,
|
9
|
+
`flask_app.py`).
|
10
|
+
"""
|
11
|
+
|
12
|
+
from typing import Optional, Callable
|
13
|
+
import json
|
14
|
+
|
15
|
+
from bisslog_schema import read_full_service_metadata
|
16
|
+
from bisslog_schema.eager_import_module_or_package import EagerImportModulePackage
|
17
|
+
from bisslog_schema.schema import UseCaseInfo, TriggerHttp, TriggerWebsocket
|
18
|
+
from bisslog_schema.setup import get_setup_metadata
|
19
|
+
from bisslog_schema.use_case_code_inspector.use_case_code_metadata import UseCaseCodeInfo, \
|
20
|
+
UseCaseCodeInfoClass, UseCaseCodeInfoObject
|
21
|
+
|
22
|
+
from .static_python_construct_data import StaticPythonConstructData
|
23
|
+
|
24
|
+
|
25
|
+
class BuilderFlaskAppManager:
|
26
|
+
"""
|
27
|
+
Flask application builder for Bisslog-based services.
|
28
|
+
|
29
|
+
This class dynamically generates Flask code based on user-declared metadata and
|
30
|
+
the implementation of use cases discovered in the source tree. It supports HTTP
|
31
|
+
and WebSocket triggers, integrates runtime setup from decorators, and configures
|
32
|
+
environment-based security.
|
33
|
+
|
34
|
+
The result is a complete Flask application scaffold that can be directly executed
|
35
|
+
or used as a starting point for further customization.
|
36
|
+
"""
|
37
|
+
|
38
|
+
def __init__(self, eager_importer: Callable[[str], None]):
|
39
|
+
self._eager_importer = eager_importer
|
40
|
+
|
41
|
+
|
42
|
+
def _get_bisslog_setup(self, infra_path: Optional[str]) -> Optional[StaticPythonConstructData]:
|
43
|
+
"""
|
44
|
+
Retrieves the Bisslog setup call for the 'flask' runtime, if defined.
|
45
|
+
|
46
|
+
This inspects the global Bisslog configuration and returns the corresponding
|
47
|
+
setup function call code for Flask.
|
48
|
+
|
49
|
+
Returns
|
50
|
+
-------
|
51
|
+
Optional[StaticPythonConstructData]
|
52
|
+
The setup code and imports, or None if no setup was declared.
|
53
|
+
"""
|
54
|
+
self._eager_importer(infra_path)
|
55
|
+
setup_metadata = get_setup_metadata()
|
56
|
+
if setup_metadata is None:
|
57
|
+
return None
|
58
|
+
|
59
|
+
if setup_metadata.setup_function is not None:
|
60
|
+
n_params = setup_metadata.setup_function.n_params
|
61
|
+
if n_params == 0:
|
62
|
+
build = f"{setup_metadata.setup_function.function_name}()"
|
63
|
+
elif n_params == 1:
|
64
|
+
build = f"{setup_metadata.setup_function.function_name}(\"flask\")"
|
65
|
+
else:
|
66
|
+
build = (f"{setup_metadata.setup_function.function_name}(\"flask\")"
|
67
|
+
" # TODO: change this")
|
68
|
+
return StaticPythonConstructData(
|
69
|
+
importing={setup_metadata.setup_function.module:
|
70
|
+
{setup_metadata.setup_function.function_name}},
|
71
|
+
build=build,
|
72
|
+
)
|
73
|
+
custom_runtime_setup = setup_metadata.runtime.get("flask", None)
|
74
|
+
if custom_runtime_setup is not None:
|
75
|
+
return StaticPythonConstructData(
|
76
|
+
importing={custom_runtime_setup.module:
|
77
|
+
{custom_runtime_setup.function_name}},
|
78
|
+
build=f"{custom_runtime_setup.function_name}()"
|
79
|
+
)
|
80
|
+
return None
|
81
|
+
|
82
|
+
@staticmethod
|
83
|
+
def _generate_security_code() -> StaticPythonConstructData:
|
84
|
+
"""
|
85
|
+
Generates Flask configuration code for secret keys using environment variables.
|
86
|
+
|
87
|
+
Returns
|
88
|
+
-------
|
89
|
+
StaticPythonConstructData
|
90
|
+
Code that assigns `SECRET_KEY` and `JWT_SECRET_KEY` to the Flask app.
|
91
|
+
"""
|
92
|
+
build = """
|
93
|
+
if "SECRET_KEY" in os.environ:
|
94
|
+
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
|
95
|
+
if "JWT_SECRET_KEY" in os.environ:
|
96
|
+
app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET_KEY"]
|
97
|
+
"""
|
98
|
+
return StaticPythonConstructData(build=build)
|
99
|
+
|
100
|
+
@staticmethod
|
101
|
+
def _generate_use_case_code_build(use_case_code_info: UseCaseCodeInfo):
|
102
|
+
"""
|
103
|
+
Prepares the use case callable to be used in HTTP or WebSocket routes.
|
104
|
+
|
105
|
+
If the use case is a class, an instance is created. If it's an object, it's referenced.
|
106
|
+
|
107
|
+
Parameters
|
108
|
+
----------
|
109
|
+
use_case_code_info : UseCaseCodeInfo
|
110
|
+
Static metadata about the use case implementation.
|
111
|
+
|
112
|
+
Returns
|
113
|
+
-------
|
114
|
+
Tuple[str, StaticPythonConstructData]
|
115
|
+
- Name of the callable reference (e.g., variable or instance).
|
116
|
+
- Generated setup code and required imports.
|
117
|
+
"""
|
118
|
+
importing = {"flask": {"request"}, "bisslog.utils.mapping": {"Mapper"}}
|
119
|
+
starting_build = ""
|
120
|
+
if isinstance(use_case_code_info, UseCaseCodeInfoClass):
|
121
|
+
importing[use_case_code_info.module] = {use_case_code_info.class_name}
|
122
|
+
uc_callable = f"{use_case_code_info.name}_uc"
|
123
|
+
starting_build += f"{uc_callable} = {use_case_code_info.class_name}()"
|
124
|
+
elif isinstance(use_case_code_info, UseCaseCodeInfoObject):
|
125
|
+
importing[use_case_code_info.module] = {use_case_code_info.var_name}
|
126
|
+
uc_callable = use_case_code_info.var_name
|
127
|
+
else:
|
128
|
+
raise ValueError("Unsupported UseCaseCodeInfo type")
|
129
|
+
return uc_callable, StaticPythonConstructData(build=starting_build, importing=importing)
|
130
|
+
|
131
|
+
@staticmethod
|
132
|
+
def _generate_use_case_code_http_trigger(
|
133
|
+
use_case_key: str, uc_callable: str, use_case_code_info: UseCaseCodeInfo,
|
134
|
+
trigger_info: TriggerHttp, identifier: int) -> StaticPythonConstructData:
|
135
|
+
"""
|
136
|
+
Generates the code for a use case with an HTTP trigger.
|
137
|
+
|
138
|
+
Parameters
|
139
|
+
----------
|
140
|
+
use_case_key : str
|
141
|
+
Name used to identify the use case route.
|
142
|
+
use_case_code_info : UseCaseCodeInfo
|
143
|
+
Static code metadata for the specific use case.
|
144
|
+
trigger_info : TriggerHttp
|
145
|
+
Metadata of the HTTP trigger.
|
146
|
+
|
147
|
+
Returns
|
148
|
+
-------
|
149
|
+
StaticPythonConstructData
|
150
|
+
The generated code for the HTTP trigger.
|
151
|
+
"""
|
152
|
+
imports = {
|
153
|
+
"flask": {"jsonify"}
|
154
|
+
}
|
155
|
+
starting_build = ""
|
156
|
+
mapper_code_lines = []
|
157
|
+
if trigger_info.mapper is not None:
|
158
|
+
mapper_name = f"{use_case_code_info.name}_mapper_{identifier}"
|
159
|
+
starting_build += (f"\n{mapper_name} = Mapper(name=\"{use_case_key}_mapper\", "
|
160
|
+
f"base={json.dumps(trigger_info.mapper)})")
|
161
|
+
mapper_code_lines.append(f"""
|
162
|
+
res_map = {mapper_name}.map({{
|
163
|
+
"path_query": route_vars,
|
164
|
+
"body": request.get_json(silent=True) or {{}},
|
165
|
+
"params": request.args.to_dict(),
|
166
|
+
"headers": request.headers,
|
167
|
+
}})""")
|
168
|
+
method = trigger_info.method.upper()
|
169
|
+
flask_path = (trigger_info.path or f"/{use_case_key}").replace("{", "<").replace("}", ">")
|
170
|
+
handler_name = f"{use_case_key}_handler_{identifier}"
|
171
|
+
|
172
|
+
lines = [
|
173
|
+
f'@app.route("{flask_path}", methods=["{method}"])',
|
174
|
+
]
|
175
|
+
|
176
|
+
if use_case_code_info.is_coroutine:
|
177
|
+
lines.append(f"async def {handler_name}(**route_vars):")
|
178
|
+
else:
|
179
|
+
lines.append(f"def {handler_name}(**route_vars):")
|
180
|
+
|
181
|
+
if not mapper_code_lines:
|
182
|
+
lines.append(" kwargs = {}")
|
183
|
+
lines.append(" kwargs.update(route_vars)")
|
184
|
+
lines.append(" kwargs.update(request.get_json(silent=True) or {})")
|
185
|
+
lines.append(" kwargs.update(request.args.to_dict())")
|
186
|
+
lines.append(" kwargs.update(dict(request.headers))")
|
187
|
+
var_to_unpack = "kwargs"
|
188
|
+
else:
|
189
|
+
lines.extend(mapper_code_lines)
|
190
|
+
var_to_unpack = "res_map"
|
191
|
+
|
192
|
+
if use_case_code_info.is_coroutine:
|
193
|
+
lines.append(f' result = await {uc_callable}(**{var_to_unpack})')
|
194
|
+
else:
|
195
|
+
lines.append(f' result = {uc_callable}(**{var_to_unpack})\n')
|
196
|
+
|
197
|
+
lines.append(' return jsonify(result)\n')
|
198
|
+
|
199
|
+
return StaticPythonConstructData(build=starting_build,
|
200
|
+
body="\n".join(lines), importing=imports)
|
201
|
+
|
202
|
+
@staticmethod
|
203
|
+
def _generate_use_case_code_websocket_trigger(
|
204
|
+
use_case_key: str,
|
205
|
+
uc_callable: str,
|
206
|
+
use_case_code_info: UseCaseCodeInfo,
|
207
|
+
trigger_info: TriggerWebsocket,
|
208
|
+
identifier: int
|
209
|
+
) -> StaticPythonConstructData:
|
210
|
+
"""
|
211
|
+
Generates the code for a use case with a WebSocket trigger using flask-sock.
|
212
|
+
|
213
|
+
Parameters
|
214
|
+
----------
|
215
|
+
use_case_key : str
|
216
|
+
The identifier of the use case.
|
217
|
+
uc_callable : str
|
218
|
+
The callable name to invoke.
|
219
|
+
use_case_code_info : UseCaseCodeInfo
|
220
|
+
Info about where the use case is defined.
|
221
|
+
trigger_info : TriggerWebsocket
|
222
|
+
Metadata describing the trigger.
|
223
|
+
identifier : int
|
224
|
+
An integer used to ensure uniqueness of function names.
|
225
|
+
|
226
|
+
Returns
|
227
|
+
-------
|
228
|
+
StaticPythonConstructData
|
229
|
+
Code and imports needed for WebSocket registration.
|
230
|
+
"""
|
231
|
+
route_key = trigger_info.route_key or f"{use_case_key}.default"
|
232
|
+
handler_name = f"{use_case_key}_ws_handler_{identifier}"
|
233
|
+
mapper_decl = ""
|
234
|
+
|
235
|
+
imports = {
|
236
|
+
use_case_code_info.module: {use_case_code_info.name},
|
237
|
+
"flask_sock": {"Sock"},
|
238
|
+
"flask": {"request", "jsonify"},
|
239
|
+
"bisslog.utils.mapping": {"Mapper"},
|
240
|
+
"json": None
|
241
|
+
}
|
242
|
+
|
243
|
+
if trigger_info.mapper:
|
244
|
+
mapper_var = f"{use_case_key}_ws_mapper_{identifier}"
|
245
|
+
mapper_json = json.dumps(trigger_info.mapper)
|
246
|
+
mapper_decl = (f'\n{mapper_var} = Mapper(name="{use_case_key}_ws_mapper",'
|
247
|
+
f' base={mapper_json})')
|
248
|
+
|
249
|
+
mapper_code = f"""
|
250
|
+
try:
|
251
|
+
body = json.loads(data)
|
252
|
+
except Exception:
|
253
|
+
body = {{}}
|
254
|
+
res_map = {mapper_var}.map({{
|
255
|
+
"route_key": "{route_key}",
|
256
|
+
"connection_id": request.headers.get("Sec-WebSocket-Key"),
|
257
|
+
"headers": request.headers,
|
258
|
+
"body": body
|
259
|
+
}})
|
260
|
+
response = {uc_callable}(**res_map)
|
261
|
+
"""
|
262
|
+
|
263
|
+
else:
|
264
|
+
# fallback: pass entire raw message
|
265
|
+
mapper_code = f"""
|
266
|
+
try:
|
267
|
+
payload = json.loads(data)
|
268
|
+
except Exception:
|
269
|
+
payload = {{}}
|
270
|
+
response = {uc_callable}(**payload)
|
271
|
+
"""
|
272
|
+
|
273
|
+
build = f"""
|
274
|
+
@sock.route("/ws/{route_key}")
|
275
|
+
def {handler_name}(ws):
|
276
|
+
while True:
|
277
|
+
data = ws.receive()
|
278
|
+
if data is None:
|
279
|
+
break; # Client disconnected
|
280
|
+
{mapper_code}
|
281
|
+
if response is not None:
|
282
|
+
ws.send(response)
|
283
|
+
"""
|
284
|
+
|
285
|
+
return StaticPythonConstructData(
|
286
|
+
importing=imports,
|
287
|
+
build=(mapper_decl + build)
|
288
|
+
)
|
289
|
+
|
290
|
+
def __call__(self,
|
291
|
+
metadata_file: Optional[str] = None,
|
292
|
+
use_cases_folder_path: Optional[str] = None,
|
293
|
+
infra_path: Optional[str] = None,
|
294
|
+
*,
|
295
|
+
encoding: str = "utf-8",
|
296
|
+
secret_key: Optional[str] = None,
|
297
|
+
jwt_secret_key: Optional[str] = None,
|
298
|
+
**kwargs) -> str:
|
299
|
+
"""
|
300
|
+
Main entry point for generating the full Flask application code.
|
301
|
+
|
302
|
+
This method orchestrates metadata loading, trigger processing, and Flask code generation
|
303
|
+
(HTTP routes, WebSocket handlers, runtime setup, security config). The resulting app code
|
304
|
+
is returned as a ready-to-write Python string.
|
305
|
+
|
306
|
+
Parameters
|
307
|
+
----------
|
308
|
+
metadata_file : str, optional
|
309
|
+
Path to the YAML or JSON metadata file.
|
310
|
+
use_cases_folder_path : str, optional
|
311
|
+
Path to the folder where use case implementations are located.
|
312
|
+
infra_path : str, optional
|
313
|
+
Path to additional infrastructure or adapter code.
|
314
|
+
encoding : str, default="utf-8"
|
315
|
+
Encoding used to read the metadata file.
|
316
|
+
secret_key : str, optional
|
317
|
+
secret key for Flask configuration.
|
318
|
+
jwt_secret_key : str, optional
|
319
|
+
JWT secret key for Flask configuration.
|
320
|
+
**kwargs
|
321
|
+
Additional keyword arguments (currently unused).
|
322
|
+
|
323
|
+
Returns
|
324
|
+
-------
|
325
|
+
str
|
326
|
+
The complete Flask application source code as a string.
|
327
|
+
"""
|
328
|
+
full_service_metadata = read_full_service_metadata(
|
329
|
+
metadata_file=metadata_file,
|
330
|
+
use_cases_folder_path=use_cases_folder_path,
|
331
|
+
encoding=encoding
|
332
|
+
)
|
333
|
+
service_info = full_service_metadata.declared_metadata
|
334
|
+
use_cases = full_service_metadata.discovered_use_cases
|
335
|
+
|
336
|
+
res = StaticPythonConstructData(
|
337
|
+
importing={"flask": {"Flask"}, "os": None},
|
338
|
+
build="app = Flask(__name__)"
|
339
|
+
)
|
340
|
+
res += self._get_bisslog_setup(infra_path)
|
341
|
+
|
342
|
+
res += self._generate_security_code()
|
343
|
+
|
344
|
+
# Use cases
|
345
|
+
for use_case_key in service_info.use_cases:
|
346
|
+
use_case_info: UseCaseInfo = service_info.use_cases[use_case_key]
|
347
|
+
use_case_code_info: UseCaseCodeInfo = use_cases[use_case_key]
|
348
|
+
triggers_http = [t for t in use_case_info.triggers
|
349
|
+
if isinstance(t.options, TriggerHttp)]
|
350
|
+
triggers_ws = [t for t in use_case_info.triggers
|
351
|
+
if isinstance(t.options, TriggerWebsocket)]
|
352
|
+
triggers_flask = triggers_http + triggers_ws
|
353
|
+
if len(triggers_flask) == 0:
|
354
|
+
continue
|
355
|
+
uc_callable, res_uc = self._generate_use_case_code_build(use_case_code_info)
|
356
|
+
res += res_uc
|
357
|
+
for i, trigger in enumerate(triggers_flask):
|
358
|
+
if isinstance(trigger.options, TriggerHttp):
|
359
|
+
res += self._generate_use_case_code_http_trigger(
|
360
|
+
use_case_key, uc_callable, use_case_code_info, trigger.options, i
|
361
|
+
)
|
362
|
+
elif isinstance(trigger.options, TriggerWebsocket):
|
363
|
+
res += self._generate_use_case_code_websocket_trigger(
|
364
|
+
use_case_key, uc_callable, use_case_code_info, trigger.options, i
|
365
|
+
)
|
366
|
+
res += StaticPythonConstructData(body='\nif __name__ == "__main__":\n'
|
367
|
+
' app.run(debug=True, host="0.0.0.0")')
|
368
|
+
return res.generate_boiler_plate_flask()
|
369
|
+
|
370
|
+
|
371
|
+
bisslog_flask_builder = BuilderFlaskAppManager(EagerImportModulePackage(("src.infra", "infra")))
|