bisslog-flask 0.0.1__py3-none-any.whl → 0.0.2__py3-none-any.whl

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.
File without changes
@@ -0,0 +1,353 @@
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
+ from typing import Optional, Callable
12
+ import json
13
+
14
+ from bisslog_schema import read_full_service_metadata
15
+ from bisslog_schema.eager_import_module_or_package import EagerImportModulePackage
16
+ from bisslog_schema.schema import UseCaseInfo, TriggerHttp, TriggerWebsocket
17
+ from bisslog_schema.setup import get_setup_metadata
18
+ from bisslog_schema.use_case_code_inspector.use_case_code_metadata import UseCaseCodeInfo, \
19
+ UseCaseCodeInfoClass, UseCaseCodeInfoObject
20
+ from .static_python_construct_data import StaticPythonConstructData
21
+
22
+
23
+ class BuilderFlaskAppManager:
24
+ """
25
+ Flask application builder for Bisslog-based services.
26
+
27
+ This class dynamically generates Flask code based on user-declared metadata and
28
+ the implementation of use cases discovered in the source tree. It supports HTTP
29
+ and WebSocket triggers, integrates runtime setup from decorators, and configures
30
+ environment-based security.
31
+
32
+ The result is a complete Flask application scaffold that can be directly executed
33
+ or used as a starting point for further customization.
34
+ """
35
+
36
+ def __init__(self, eager_importer: Callable[[str], None]):
37
+ self._eager_importer = eager_importer
38
+
39
+
40
+ def _get_bisslog_setup(self, infra_path: Optional[str]) -> Optional[StaticPythonConstructData]:
41
+ """
42
+ Retrieves the Bisslog setup call for the 'flask' runtime, if defined.
43
+
44
+ This inspects the global Bisslog configuration and returns the corresponding
45
+ setup function call code for Flask.
46
+
47
+ Returns
48
+ -------
49
+ Optional[StaticPythonConstructData]
50
+ The setup code and imports, or None if no setup was declared.
51
+ """
52
+ self._eager_importer(infra_path)
53
+ setup_metadata = get_setup_metadata()
54
+ if setup_metadata is None:
55
+ return None
56
+
57
+ if setup_metadata.setup_function is not None:
58
+ n_params = setup_metadata.setup_function.n_params
59
+ if n_params == 0:
60
+ build = f"{setup_metadata.setup_function.function_name}()"
61
+ elif n_params == 1:
62
+ build = f"{setup_metadata.setup_function.function_name}(\"flask\")"
63
+ else:
64
+ build = (f"{setup_metadata.setup_function.function_name}(\"flask\")"
65
+ " # TODO: change this")
66
+ return StaticPythonConstructData(
67
+ importing={setup_metadata.setup_function.module:
68
+ {setup_metadata.setup_function.function_name}},
69
+ build=build,
70
+ )
71
+ custom_runtime_setup = setup_metadata.runtime.get("flask", None)
72
+ if custom_runtime_setup is not None:
73
+ return StaticPythonConstructData(
74
+ importing={custom_runtime_setup.module:
75
+ {custom_runtime_setup.function_name}},
76
+ build=f"{custom_runtime_setup.function_name}()"
77
+ )
78
+ return None
79
+
80
+ @staticmethod
81
+ def _generate_security_code() -> StaticPythonConstructData:
82
+ """
83
+ Generates Flask configuration code for secret keys using environment variables.
84
+
85
+ Returns
86
+ -------
87
+ StaticPythonConstructData
88
+ Code that assigns `SECRET_KEY` and `JWT_SECRET_KEY` to the Flask app.
89
+ """
90
+ build = """
91
+ if "SECRET_KEY" in os.environ:
92
+ app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
93
+ if "JWT_SECRET_KEY" in os.environ:
94
+ app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET_KEY"]
95
+ """
96
+ return StaticPythonConstructData(build=build)
97
+
98
+ @staticmethod
99
+ def _generate_use_case_code_build(use_case_code_info: UseCaseCodeInfo):
100
+ """
101
+ Prepares the use case callable to be used in HTTP or WebSocket routes.
102
+
103
+ If the use case is a class, an instance is created. If it's an object, it's referenced.
104
+
105
+ Parameters
106
+ ----------
107
+ use_case_code_info : UseCaseCodeInfo
108
+ Static metadata about the use case implementation.
109
+
110
+ Returns
111
+ -------
112
+ Tuple[str, StaticPythonConstructData]
113
+ - Name of the callable reference (e.g., variable or instance).
114
+ - Generated setup code and required imports.
115
+ """
116
+ importing = {"flask": {"request"}, "bisslog.utils.mapping": {"Mapper"}}
117
+ starting_build = ""
118
+ if isinstance(use_case_code_info, UseCaseCodeInfoClass):
119
+ importing[use_case_code_info.module] = {use_case_code_info.class_name}
120
+ uc_callable = f"{use_case_code_info.name}_uc"
121
+ starting_build += f"{uc_callable} = {use_case_code_info.class_name}()"
122
+ elif isinstance(use_case_code_info, UseCaseCodeInfoObject):
123
+ importing[use_case_code_info.module] = {use_case_code_info.var_name}
124
+ uc_callable = use_case_code_info.var_name
125
+ else:
126
+ raise ValueError("Unsupported UseCaseCodeInfo type")
127
+ return uc_callable, StaticPythonConstructData(build=starting_build, importing=importing)
128
+
129
+ @staticmethod
130
+ def _generate_use_case_code_http_trigger(
131
+ use_case_key: str, uc_callable: str, use_case_code_info: UseCaseCodeInfo,
132
+ trigger_info: TriggerHttp, identifier: int) -> StaticPythonConstructData:
133
+ """
134
+ Generates the code for a use case with an HTTP trigger.
135
+
136
+ Parameters
137
+ ----------
138
+ use_case_key : str
139
+ Name used to identify the use case route.
140
+ use_case_code_info : UseCaseCodeInfo
141
+ Static code metadata for the specific use case.
142
+ trigger_info : TriggerHttp
143
+ Metadata of the HTTP trigger.
144
+
145
+ Returns
146
+ -------
147
+ StaticPythonConstructData
148
+ The generated code for the HTTP trigger.
149
+ """
150
+ starting_build = ""
151
+ mapper_code_lines = []
152
+ if trigger_info.mapper is not None:
153
+ mapper_name = f"{use_case_code_info.name}_mapper_{identifier}"
154
+ starting_build += (f"\n{mapper_name} = Mapper(name=\"{use_case_key}_mapper\", "
155
+ f"base={json.dumps(trigger_info.mapper)})")
156
+ mapper_code_lines.append(f"""
157
+ res_map = {mapper_name}.map({{
158
+ "path_query": request.view_args or {{}},
159
+ "body": request.get_json(silent=True) or {{}},
160
+ "params": request.args.to_dict(),
161
+ "headers": request.headers,
162
+ }})""")
163
+ method = trigger_info.method.upper()
164
+ flask_path = (trigger_info.path or f"/{use_case_key}").replace("{", "<").replace("}", ">")
165
+ handler_name = f"{use_case_key}_handler_{identifier}"
166
+
167
+ lines = [
168
+ f'@app.route("{flask_path}", methods=["{method}"])',
169
+ f'def {handler_name}():',
170
+ ]
171
+ if not mapper_code_lines:
172
+ lines.append(" kwargs = {}")
173
+ lines.append(" kwargs.update(request.view_args or {})")
174
+ lines.append(" kwargs.update(request.get_json(silent=True) or {})")
175
+ lines.append(" kwargs.update(request.args.to_dict())")
176
+ lines.append(" kwargs.update(dict(request.headers))")
177
+ lines.append(f" return {uc_callable}(**kwargs)\n")
178
+ else:
179
+ lines.extend(mapper_code_lines)
180
+ lines.append(f' return {uc_callable}(**res_map)\n')
181
+
182
+ return StaticPythonConstructData(build=starting_build, body="\n".join(lines))
183
+
184
+ @staticmethod
185
+ def _generate_use_case_code_websocket_trigger(
186
+ use_case_key: str,
187
+ uc_callable: str,
188
+ use_case_code_info: UseCaseCodeInfo,
189
+ trigger_info: TriggerWebsocket,
190
+ identifier: int
191
+ ) -> StaticPythonConstructData:
192
+ """
193
+ Generates the code for a use case with a WebSocket trigger using flask-sock.
194
+
195
+ Parameters
196
+ ----------
197
+ use_case_key : str
198
+ The identifier of the use case.
199
+ uc_callable : str
200
+ The callable name to invoke.
201
+ use_case_code_info : UseCaseCodeInfo
202
+ Info about where the use case is defined.
203
+ trigger_info : TriggerWebsocket
204
+ Metadata describing the trigger.
205
+ identifier : int
206
+ An integer used to ensure uniqueness of function names.
207
+
208
+ Returns
209
+ -------
210
+ StaticPythonConstructData
211
+ Code and imports needed for WebSocket registration.
212
+ """
213
+ route_key = trigger_info.route_key or f"{use_case_key}.default"
214
+ handler_name = f"{use_case_key}_ws_handler_{identifier}"
215
+ mapper_decl = ""
216
+
217
+ imports = {
218
+ use_case_code_info.module: {use_case_code_info.name},
219
+ "flask_sock": {"Sock"},
220
+ "flask": {"request"},
221
+ "bisslog.utils.mapping": {"Mapper"},
222
+ "json": None
223
+ }
224
+
225
+ if trigger_info.mapper:
226
+ mapper_var = f"{use_case_key}_ws_mapper_{identifier}"
227
+ mapper_json = json.dumps(trigger_info.mapper)
228
+ mapper_decl = (f'\n{mapper_var} = Mapper(name="{use_case_key}_ws_mapper",'
229
+ f' base={mapper_json})')
230
+
231
+ mapper_code = f"""
232
+ try:
233
+ body = json.loads(data)
234
+ except Exception:
235
+ body = {{}}
236
+ res_map = {mapper_var}.map({{
237
+ "route_key": "{route_key}",
238
+ "connection_id": request.headers.get("Sec-WebSocket-Key"),
239
+ "headers": request.headers,
240
+ "body": body
241
+ }})
242
+ response = {uc_callable}(**res_map)
243
+ """
244
+
245
+ else:
246
+ # fallback: pass entire raw message
247
+ mapper_code = f"""
248
+ try:
249
+ payload = json.loads(data)
250
+ except Exception:
251
+ payload = {{}}
252
+ response = {uc_callable}(**payload)
253
+ """
254
+
255
+ build = f"""
256
+ @sock.route("/ws/{route_key}")
257
+ def {handler_name}(ws):
258
+ while True:
259
+ data = ws.receive()
260
+ if data is None:
261
+ break; # Client disconnected
262
+ {mapper_code}
263
+ if response is not None:
264
+ ws.send(response)
265
+ """
266
+
267
+ return StaticPythonConstructData(
268
+ importing=imports,
269
+ build=(mapper_decl + build)
270
+ )
271
+
272
+ def __call__(self,
273
+ metadata_file: Optional[str] = None,
274
+ use_cases_folder_path: Optional[str] = None,
275
+ infra_path: Optional[str] = None,
276
+ *,
277
+ encoding: str = "utf-8",
278
+ secret_key: Optional[str] = None,
279
+ jwt_secret_key: Optional[str] = None,
280
+ **kwargs) -> str:
281
+ """
282
+ Main entry point for generating the full Flask application code.
283
+
284
+ This method orchestrates metadata loading, trigger processing, and Flask code generation
285
+ (HTTP routes, WebSocket handlers, runtime setup, security config). The resulting app code
286
+ is returned as a ready-to-write Python string.
287
+
288
+ Parameters
289
+ ----------
290
+ metadata_file : str, optional
291
+ Path to the YAML or JSON metadata file.
292
+ use_cases_folder_path : str, optional
293
+ Path to the folder where use case implementations are located.
294
+ infra_path : str, optional
295
+ Path to additional infrastructure or adapter code.
296
+ encoding : str, default="utf-8"
297
+ Encoding used to read the metadata file.
298
+ secret_key : str, optional
299
+ secret key for Flask configuration.
300
+ jwt_secret_key : str, optional
301
+ JWT secret key for Flask configuration.
302
+ **kwargs
303
+ Additional keyword arguments (currently unused).
304
+
305
+ Returns
306
+ -------
307
+ str
308
+ The complete Flask application source code as a string.
309
+ """
310
+ full_service_metadata = read_full_service_metadata(
311
+ metadata_file=metadata_file,
312
+ use_cases_folder_path=use_cases_folder_path,
313
+ encoding=encoding
314
+ )
315
+ service_info = full_service_metadata.declared_metadata
316
+ use_cases = full_service_metadata.discovered_use_cases
317
+
318
+ res = StaticPythonConstructData(
319
+ importing={"flask": {"Flask"}, "os": None},
320
+ build="app = Flask(__name__)"
321
+ )
322
+ res += self._get_bisslog_setup(infra_path)
323
+
324
+ res += self._generate_security_code()
325
+
326
+ # Use cases
327
+ for use_case_key in service_info.use_cases:
328
+ use_case_info: UseCaseInfo = service_info.use_cases[use_case_key]
329
+ use_case_code_info: UseCaseCodeInfo = use_cases[use_case_key]
330
+ triggers_http = [t for t in use_case_info.triggers
331
+ if isinstance(t.options, TriggerHttp)]
332
+ triggers_ws = [t for t in use_case_info.triggers
333
+ if isinstance(t.options, TriggerWebsocket)]
334
+ triggers_flask = triggers_http + triggers_ws
335
+ if len(triggers_flask) == 0:
336
+ continue
337
+ uc_callable, res_uc = self._generate_use_case_code_build(use_case_code_info)
338
+ res += res_uc
339
+ for i, trigger in enumerate(triggers_flask):
340
+ if isinstance(trigger.options, TriggerHttp):
341
+ res += self._generate_use_case_code_http_trigger(
342
+ use_case_key, uc_callable, use_case_code_info, trigger.options, i
343
+ )
344
+ elif isinstance(trigger.options, TriggerWebsocket):
345
+ res += self._generate_use_case_code_websocket_trigger(
346
+ use_case_key, uc_callable, use_case_code_info, trigger.options, i
347
+ )
348
+ res += StaticPythonConstructData(body='\nif __name__ == "__main__":\n'
349
+ ' app.run(debug=True, host="0.0.0.0")')
350
+ return res.generate_boiler_plate_flask()
351
+
352
+
353
+ bisslog_flask_builder = BuilderFlaskAppManager(EagerImportModulePackage(("src.infra", "infra")))
@@ -0,0 +1,172 @@
1
+ """
2
+ Module defining the response structure for AWS Lambda handler code generation.
3
+
4
+ This module provides a dataclass that encapsulates the components produced during
5
+ AWS Lambda handler code generation, including the function body, optional setup code,
6
+ and required import statements.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Optional, Dict, Any, Set
11
+
12
+
13
+
14
+ @dataclass
15
+ class StaticPythonConstructData:
16
+ """
17
+ Response structure for generated AWS Lambda handler components.
18
+
19
+ This dataclass represents the output of a code generator that produces AWS Lambda
20
+ handler functions. It contains the function body as a string, any optional setup/build
21
+ logic, and the necessary import statements grouped by module.
22
+
23
+ Attributes
24
+ ----------
25
+ body : Optional[str]
26
+ The body of the Lambda handler function as a Python code string.
27
+ build : Optional[str]
28
+ Optional setup or preconstruction code to include before the function body.
29
+ importing : Dict[str, Set[str]]
30
+ A mapping of module names to sets of symbols to import from them.
31
+
32
+ This structure assumes simple `from module import symbol` semantics.
33
+
34
+ Examples
35
+ --------
36
+ {
37
+ "typing": {"List", "Optional"},
38
+ "os": {"path", "environ"}
39
+ }
40
+
41
+ extra : Dict[str, Any]
42
+ Optional extra data provided by the generator.
43
+ """
44
+ body: Optional[str] = None
45
+ build: Optional[str] = None
46
+ importing: Dict[str, Set[str]] = field(default_factory=dict)
47
+ extra: Dict[str, Any] = field(default_factory=dict)
48
+
49
+ def add_imports(self, new_imports: Dict[str, Set[str]]) -> None:
50
+ """
51
+ Adds new import statements to the existing import dictionary.
52
+
53
+ Parameters
54
+ ----------
55
+ new_imports : Dict[str, Set[str]]
56
+ A dictionary of module names and symbols to import.
57
+ """
58
+ for module, symbols in new_imports.items():
59
+ if module not in self.importing:
60
+ self.importing[module] = set()
61
+ self.importing[module].update(symbols)
62
+
63
+ @staticmethod
64
+ def _generate_imports_string(imports: Dict[str, Set[str]]) -> str:
65
+ """
66
+ Generates a string representing import statements.
67
+
68
+ Parameters
69
+ ----------
70
+ imports : Dict[str, Set[str]]
71
+ A dictionary where keys are module names and values are sets of symbols.
72
+
73
+ Returns
74
+ -------
75
+ str
76
+ Formatted import statements, one per line.
77
+ """
78
+ return "\n".join(
79
+ f"from {source} import {', '.join(sorted(var))}" if var else f"import {source}"
80
+ for source, var in imports.items()
81
+ )
82
+
83
+ def generate_boiler_plate_flask(self) -> str:
84
+ """
85
+ Builds the final AWS Lambda handler code as a complete Python string.
86
+
87
+ This includes import statements, any pre-construction logic, and
88
+ the `lambda_handler` function definition.
89
+
90
+ Returns
91
+ -------
92
+ str
93
+ The full source code of the handler as a string.
94
+ """
95
+ imports_chunk = self._generate_imports_string(self.importing)
96
+ sep = "\n" * 3
97
+ return f"{imports_chunk}{sep}{self.build or ''}{sep}{self.body or ''}\n"
98
+
99
+ def __add__(self, other: "StaticPythonConstructData") -> "StaticPythonConstructData":
100
+ """
101
+ Combine two AWSHandlerGenResponse objects by merging their fields.
102
+
103
+ Parameters
104
+ ----------
105
+ other : StaticPythonConstructData
106
+ Another response to merge.
107
+
108
+ Returns
109
+ -------
110
+ StaticPythonConstructData
111
+ A new instance with merged content.
112
+
113
+ Raises
114
+ ------
115
+ NotImplementedError
116
+ If `other` is not an instance of AWSHandlerGenResponse.
117
+ """
118
+ if not isinstance(other, StaticPythonConstructData):
119
+ raise NotImplementedError
120
+
121
+ merged_body = "\n".join(filter(None, [self.body, other.body])) or None
122
+ merged_build = "\n".join(filter(None, [self.build, other.build])) or None
123
+
124
+ merged_importing: Dict[str, Set[str]] = {}
125
+ for module in set(self.importing) | set(other.importing):
126
+ symbols_self = self.importing.get(module, set())
127
+ symbols_other = other.importing.get(module, set())
128
+ merged_importing[module] = symbols_self.union(symbols_other)
129
+
130
+ return StaticPythonConstructData(
131
+ body=merged_body,
132
+ build=merged_build,
133
+ importing=merged_importing,
134
+ extra={}
135
+ )
136
+
137
+ def __iadd__(self, other: "StaticPythonConstructData") -> "StaticPythonConstructData":
138
+ """
139
+ In-place addition of another AWSHandlerGenResponse instance.
140
+
141
+ Modifies the current instance by merging the fields from `other`.
142
+
143
+ Parameters
144
+ ----------
145
+ other : StaticPythonConstructData
146
+ The response to merge into this one.
147
+
148
+ Returns
149
+ -------
150
+ StaticPythonConstructData
151
+ The modified instance (`self`).
152
+
153
+ Raises
154
+ ------
155
+ NotImplementedError
156
+ If `other` is not an instance of AWSHandlerGenResponse.
157
+ """
158
+ if other is None:
159
+ return self
160
+ if not isinstance(other, StaticPythonConstructData):
161
+ raise NotImplementedError
162
+
163
+ self.body = "\n".join(filter(None, [self.body, other.body])) or None
164
+ self.build = "\n".join(filter(None, [self.build, other.build])) or None
165
+
166
+ for module, symbols in other.importing.items():
167
+ if module not in self.importing:
168
+ self.importing[module] = set()
169
+ self.importing[module].update(symbols)
170
+
171
+ self.extra = {}
172
+ return self
@@ -0,0 +1,88 @@
1
+ import os
2
+ import sys
3
+ import argparse
4
+ import traceback
5
+
6
+ from .commands.run import run
7
+ from .commands.build import build_boiler_plate_flask
8
+
9
+
10
+ def main():
11
+ """
12
+ Entry point for the `bisslog_flask` command-line interface.
13
+
14
+ This function parses command-line arguments and executes the corresponding
15
+ subcommand. Currently, it supports the `run` and `build` commands.
16
+
17
+ Commands
18
+ --------
19
+ run
20
+ Starts a Flask application based on provided metadata and use case folder.
21
+
22
+ build
23
+ Generates a Flask boilerplate app file from metadata and use cases.
24
+
25
+ Raises
26
+ ------
27
+ Exception
28
+ Any exception raised during command execution is caught and printed to stderr.
29
+ """
30
+ project_root = os.getcwd()
31
+
32
+ if project_root not in sys.path:
33
+ sys.path.insert(0, project_root)
34
+
35
+ parser = argparse.ArgumentParser(prog="bisslog_flask")
36
+ subparsers = parser.add_subparsers(dest="command", required=True)
37
+
38
+ # Define `run` command
39
+ run_parser = subparsers.add_parser("run", help="Run a Flask app using metadata.")
40
+ run_parser.add_argument("--metadata-file", type=str, default=None,
41
+ help="Path to metadata file (YAML or JSON).")
42
+ run_parser.add_argument("--use-cases-folder-path", type=str, default=None,
43
+ help="Path to use case source folder.")
44
+ run_parser.add_argument("--infra-path", type=str, default=None,
45
+ help="Path to infrastructure code folder (optional).")
46
+ run_parser.add_argument("--encoding", type=str, default="utf-8",
47
+ help="File encoding (default: utf-8).")
48
+ run_parser.add_argument("--secret-key", type=str,
49
+ help="Flask SECRET_KEY config value.")
50
+ run_parser.add_argument("--jwt-secret-key", type=str,
51
+ help="Flask JWT_SECRET_KEY config value.")
52
+
53
+ # Define `build` command
54
+ build_parser = subparsers.add_parser("build",
55
+ help="Generate a Flask app boilerplate file.")
56
+ build_parser.add_argument("--metadata-file", type=str, default=None,
57
+ help="Path to metadata file (YAML or JSON).")
58
+ build_parser.add_argument("--use-cases-folder-path", type=str, default=None,
59
+ help="Path to use case source folder.")
60
+ build_parser.add_argument("--infra-path", type=str, default=None,
61
+ help="Path to infrastructure code folder (optional).")
62
+ build_parser.add_argument("--encoding", type=str, default="utf-8",
63
+ help="File encoding (default: utf-8).")
64
+ build_parser.add_argument("--target-filename", type=str, default="flask_app.py",
65
+ help="Filename to write the generated boilerplate (default: flask_app.py)")
66
+
67
+ args = parser.parse_args()
68
+
69
+ try:
70
+ if args.command == "run":
71
+ run(metadata_file=args.metadata_file,
72
+ use_cases_folder_path=args.use_cases_folder_path,
73
+ infra_path=args.infra_path,
74
+ encoding=args.encoding,
75
+ secret_key=args.secret_key,
76
+ jwt_secret_key=args.jwt_secret_key)
77
+ elif args.command == "build":
78
+ build_boiler_plate_flask(
79
+ metadata_file=args.metadata_file,
80
+ use_cases_folder_path=args.use_cases_folder_path,
81
+ infra_path=args.infra_path,
82
+ encoding=args.encoding,
83
+ target_filename=args.target_filename
84
+ )
85
+ except Exception as e:
86
+ traceback.print_exc()
87
+ print(e)
88
+ sys.exit(1)
File without changes
@@ -0,0 +1,55 @@
1
+ """
2
+ CLI-compatible utility for generating a Flask application boilerplate from Bisslog metadata.
3
+
4
+ This module defines a function that reads service metadata and discovered use cases,
5
+ generates the corresponding Flask application source code, and writes it to a file.
6
+ It is intended to be used as part of a command-line interface or automation script
7
+ to scaffold ready-to-run Flask services.
8
+
9
+ The generated code supports HTTP and WebSocket routes, environment-based security
10
+ configuration, and respects the Bisslog runtime setup defined via decorators.
11
+ """
12
+ from typing import Optional
13
+ from ...builder.builder_flask_app_manager import bisslog_flask_builder
14
+
15
+ def build_boiler_plate_flask(
16
+ metadata_file: Optional[str] = None,
17
+ use_cases_folder_path: Optional[str] = None,
18
+ infra_path: Optional[str] = None,
19
+ encoding: str = "utf-8",
20
+ target_filename: str = "flask_app.py"
21
+ ):
22
+ """
23
+ Generates a Flask application boilerplate file from Bisslog metadata and use case code.
24
+
25
+ This function loads the service metadata and associated use cases, builds the Flask
26
+ application source code dynamically, and writes it to a Python file (e.g., `flask_app.py`).
27
+ The generated app includes route registration, security setup, and optional WebSocket support.
28
+
29
+ Parameters
30
+ ----------
31
+ metadata_file : str, optional
32
+ Path to the YAML or JSON metadata file describing the service.
33
+ use_cases_folder_path : str, optional
34
+ Path to the folder where the use case implementations are located.
35
+ infra_path : str, optional
36
+ Path to the folder where infrastructure components (e.g., adapters) are defined.
37
+ encoding : str, default="utf-8"
38
+ The file encoding to use when reading and writing files.
39
+ target_filename : str, default="flask_app.py"
40
+ The output filename where the Flask boilerplate code will be written.
41
+
42
+ Returns
43
+ -------
44
+ None
45
+ This function writes the generated Flask app code directly to the specified file.
46
+ """
47
+ flask_boiler_plate_string = bisslog_flask_builder(
48
+ metadata_file=metadata_file,
49
+ use_cases_folder_path=use_cases_folder_path,
50
+ infra_path=infra_path,
51
+ encoding=encoding
52
+ )
53
+
54
+ with open(target_filename, "w", encoding=encoding) as f:
55
+ f.write(flask_boiler_plate_string)
@@ -0,0 +1,52 @@
1
+ """
2
+ Command module to run a Flask application using Bisslog metadata.
3
+
4
+ This module provides a simple `run` function that initializes a Flask app
5
+ with use case metadata and launches the server. It is intended to be used
6
+ by the `bisslog_flask run` CLI command or directly from Python code.
7
+ """
8
+
9
+ from typing import Optional
10
+
11
+ from bisslog_flask import BisslogFlask
12
+
13
+
14
+ def run(metadata_file: Optional[str] = None,
15
+ use_cases_folder_path: Optional[str] = None,
16
+ infra_path: Optional[str] = None,
17
+ encoding: str = "utf-8",
18
+ secret_key: Optional[str] = None,
19
+ jwt_secret_key: Optional[str] = None):
20
+ """
21
+ Run a Flask application using metadata and use case source.
22
+
23
+ This function creates and runs a Flask app configured through the
24
+ BisslogFlask integration layer. It loads metadata definitions,
25
+ applies HTTP and WebSocket use case resolvers, and starts the server.
26
+
27
+ Parameters
28
+ ----------
29
+ metadata_file : str, optional
30
+ Path to the metadata file (YAML or JSON) containing service and trigger definitions.
31
+ use_cases_folder_path : str, optional
32
+ Path to the folder where the use case implementation code is located.
33
+ infra_path : str, optional
34
+ Path to the folder containing infrastructure code (e.g., database, cache).
35
+ This is not used in the current implementation but can be extended.
36
+ encoding : str, optional
37
+ Encoding used to read the metadata file (default is "utf-8").
38
+ secret_key : str, optional
39
+ Value to set as Flask's SECRET_KEY for session signing.
40
+ jwt_secret_key : str, optional
41
+ Value to set as Flask's JWT_SECRET_KEY for JWT-based authentication.
42
+ """
43
+ app = BisslogFlask(
44
+ metadata_file=metadata_file,
45
+ use_cases_folder_path=use_cases_folder_path,
46
+ infra_path=infra_path,
47
+ encoding=encoding,
48
+ secret_key=secret_key,
49
+ jwt_secret_key=jwt_secret_key
50
+ )
51
+
52
+ app.run()
@@ -18,6 +18,8 @@ Dependencies
18
18
  from typing import Optional, Callable
19
19
 
20
20
  from bisslog_schema import read_service_info_with_code
21
+ from bisslog_schema.eager_import_module_or_package import EagerImportModulePackage
22
+ from bisslog_schema.setup import run_setup
21
23
  from bisslog_schema.schema import UseCaseInfo, TriggerHttp, TriggerWebsocket
22
24
  from flask import Flask
23
25
 
@@ -42,14 +44,17 @@ class InitFlaskAppManager:
42
44
  """
43
45
 
44
46
  def __init__(self, http_processor: BisslogFlaskResolver,
45
- websocket_processor: BisslogFlaskResolver) -> None:
47
+ websocket_processor: BisslogFlaskResolver,
48
+ force_import: Callable[[str], None]) -> None:
46
49
  self._http_processor = http_processor
47
50
  self._websocket_processor = websocket_processor
51
+ self._force_import = force_import
48
52
 
49
53
  def __call__(
50
54
  self,
51
55
  metadata_file: Optional[str] = None,
52
56
  use_cases_folder_path: Optional[str] = None,
57
+ infra_path: Optional[str] = None,
53
58
  app: Optional[Flask] = None,
54
59
  *,
55
60
  encoding: str = "utf-8",
@@ -69,6 +74,9 @@ class InitFlaskAppManager:
69
74
  Path to the metadata file (YAML/JSON).
70
75
  use_cases_folder_path : str, optional
71
76
  Directory where use case code is located.
77
+ infra_path : str, optional
78
+ Path to the folder where infrastructure components (e.g., adapters) are defined.
79
+ This is used to ensure that necessary modules are imported before route registration.
72
80
  app : Flask, optional
73
81
  An existing Flask app instance to which routes will be added.
74
82
  If not provided, a new app is created using the service name.
@@ -94,6 +102,11 @@ class InitFlaskAppManager:
94
102
  service_info = full_service_data.declared_metadata
95
103
  use_cases = full_service_data.discovered_use_cases
96
104
 
105
+ # Force import
106
+ self._force_import(infra_path)
107
+ # Run global setup if defined
108
+ run_setup("flask")
109
+
97
110
  # Initialize Flask app
98
111
  if app is None:
99
112
  app = Flask(service_info.name)
@@ -120,4 +133,5 @@ class InitFlaskAppManager:
120
133
  return app
121
134
 
122
135
 
123
- BisslogFlask = InitFlaskAppManager(BisslogFlaskHttpResolver(), BisslogFlaskWebSocketResolver())
136
+ BisslogFlask = InitFlaskAppManager(BisslogFlaskHttpResolver(), BisslogFlaskWebSocketResolver(),
137
+ EagerImportModulePackage(("src.infra", "infra")))
@@ -20,9 +20,6 @@ class BisslogFlaskSocketHelper(WebSocketManager):
20
20
  a consistent interface.
21
21
  """
22
22
 
23
- def __init__(self, conn) -> None:
24
- super().__init__(conn)
25
-
26
23
  def emit(self, event: str, connection_id: str, payload: Any,
27
24
  broadcast: bool = False, to: str = None):
28
25
  """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bisslog_flask
3
- Version: 0.0.1
3
+ Version: 0.0.2
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
@@ -11,7 +11,7 @@ Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
13
  Requires-Dist: bisslog>=0.0.7
14
- Requires-Dist: bisslog-schema>=0.0.3
14
+ Requires-Dist: bisslog-schema>=0.0.6
15
15
  Requires-Dist: flask
16
16
  Provides-Extra: websocket
17
17
  Requires-Dist: flask-socketio; extra == "websocket"
@@ -19,45 +19,43 @@ Provides-Extra: cors
19
19
  Requires-Dist: flask-cors>=6.0.0; extra == "cors"
20
20
  Dynamic: license-file
21
21
 
22
-
23
22
  # bisslog-flask
24
23
 
25
24
  [![PyPI](https://img.shields.io/pypi/v/bisslog-flask)](https://pypi.org/project/bisslog-flask/)
26
25
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
27
26
 
28
- **bisslog-flask** is an extension of the bisslog library to support processes with Flask. 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.
27
+ **bisslog-flask** is an extension of the Bisslog library to support processes with Flask.
28
+ 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
29
 
30
- Part of the bisslog ecosystem, it is designed to work seamlessly with domain-centric architectures like Hexagonal or Clean Architecture.
30
+ Part of the Bisslog ecosystem, it is designed to work seamlessly with domain-centric architectures like Hexagonal or Clean Architecture.
31
31
 
32
- ## Features
32
+ ---
33
33
 
34
- - 🔁 Dynamic route registration for HTTP and WebSocket triggers
34
+ ## Features
35
35
 
36
+ - 🔁 Dynamic route registration for HTTP and WebSocket triggers
36
37
  - 🧠 Metadata-driven setup – use YAML or JSON to declare your use cases
37
-
38
- - 🔒 Automatic CORS per endpoint using flask-cors
39
-
38
+ - 🔒 Automatic CORS per endpoint using `flask-cors`
40
39
  - 🔌 Extensible resolver pattern – plug in your own processor
41
-
42
40
  - ⚙️ Mapper integration – maps HTTP request parts to domain function arguments
43
41
 
44
-
42
+ ---
45
43
 
46
44
  ## 📦 Installation
47
45
 
48
- ~~~shell
46
+ ```bash
49
47
  pip install bisslog-flask
50
- ~~~
51
-
52
-
48
+ ```
53
49
 
50
+ ---
54
51
 
55
52
  ## 🚀 Quickstart
56
53
 
57
54
  ### Programmatically
58
55
 
59
- if you want to configure the app before bisslog touches it
60
- ~~~python
56
+ Use this approach if you want to configure the app before Bisslog touches it:
57
+
58
+ ```python
61
59
  from flask import Flask
62
60
  from bisslog_flask import BisslogFlask
63
61
 
@@ -70,11 +68,11 @@ BisslogFlask(
70
68
 
71
69
  if __name__ == "__main__":
72
70
  app.run(debug=True)
73
- ~~~
71
+ ```
74
72
 
75
- or
73
+ Or use the factory version:
76
74
 
77
- ~~~python
75
+ ```python
78
76
  from bisslog_flask import BisslogFlask
79
77
 
80
78
  app = BisslogFlask(
@@ -84,58 +82,73 @@ app = BisslogFlask(
84
82
 
85
83
  if __name__ == "__main__":
86
84
  app.run(debug=True)
87
- ~~~
88
-
85
+ ```
89
86
 
87
+ ---
90
88
 
91
- ## 🔧 How It Works
89
+ ## 🖥️ CLI Usage
92
90
 
93
- 1. Loads metadata and discovers use case functions (or callables), then uses resolvers to register routes dynamically into a Flask app.
91
+ You can also use the `bisslog_flask` CLI to run or generate a Flask app.
94
92
 
93
+ ```bash
94
+ bisslog_flask run [--metadata-file FILE] [--use-cases-folder-path DIR]
95
+ [--infra-folder-path DIR] [--encoding ENC]
96
+ [--secret-key KEY] [--jwt-secret-key KEY]
95
97
 
96
- ## 🔐 CORS Handling
98
+ bisslog_flask build [--metadata-file FILE] [--use-cases-folder-path DIR]
99
+ [--infra-folder-path DIR] [--encoding ENC]
100
+ [--target-filename FILE]
101
+ ```
97
102
 
98
- CORS is applied only when allow_cors: true is specified in the trigger
103
+ - `run`: Launches the Flask application from metadata.
104
+ - `build`: Generates a boilerplate Flask file (`flask_app.py` by default).
99
105
 
100
- Fully dynamic: works even with dynamic Flask routes like /users/<id>
106
+ All options are optional. You can override defaults via CLI flags.
101
107
 
102
- Powered by `@cross_origin` from `flask-cors`
108
+ ---
103
109
 
110
+ ## 🔐 CORS Handling
104
111
 
105
- ## Requirements
112
+ CORS is applied only when `allow_cors: true` is specified in the trigger.
106
113
 
107
- Python 3.7
114
+ Fully dynamic: works even with Flask dynamic routes like `/users/<id>`.
108
115
 
109
- Flask 2.0
116
+ Powered by `@cross_origin` from `flask-cors`.
110
117
 
111
- bisslog-schema ≥ 0.0.3
118
+ ---
112
119
 
113
- flask-cors
120
+ ## ✅ Requirements
114
121
 
115
- (Optional) flask-socketio if using WebSocket triggers
122
+ - Python 3.7
123
+ - Flask ≥ 2.0
124
+ - bisslog-schema ≥ 0.0.3
125
+ - flask-cors
126
+ - (Optional) flask-sock if using WebSocket triggers
116
127
 
128
+ ---
117
129
 
118
130
  ## 🧪 Testing Tip
119
131
 
120
- You can test the generated Flask app directly with `app.test_client()` if you take the programmatic way:
132
+ You can test the generated Flask app directly with `app.test_client()` if using the programmatic interface:
121
133
 
122
134
  ```python
123
135
  from bisslog_flask import BisslogFlask
124
136
 
125
137
  def test_user_create():
126
- app = BisslogFlask(metadata_file="metadata.yml", use_cases_folder_path="src/use_cases")
138
+ app = BisslogFlask(
139
+ metadata_file="metadata.yml",
140
+ use_cases_folder_path="src/use_cases"
141
+ )
127
142
  client = app.test_client()
128
143
  response = client.post("/user", json={"name": "Ana", "email": "ana@example.com"})
129
144
  assert response.status_code == 200
130
145
  ```
131
146
 
132
- Not generating code or using the programmatic way you just need to test your use cases.
133
-
147
+ If you're generating the code (boilerplate), you just need to test your use cases.
134
148
 
149
+ ---
135
150
 
136
151
  ## 📜 License
137
152
 
138
- This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
139
-
140
-
141
-
153
+ This project is licensed under the MIT License.
154
+ See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,21 @@
1
+ bisslog_flask/__init__.py,sha256=BEf_UxFtcMfaM-Smh_bwc6Xn8pR8LcEjby3nCs0hdXE,758
2
+ bisslog_flask/builder/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ bisslog_flask/builder/builder_flask_app_manager.py,sha256=cJtbkT21lydm2tEQr3V3-7wm5ilJfJP0qFl9Oa3TpkA,14302
4
+ bisslog_flask/builder/static_python_construct_data.py,sha256=p8QcXUAXZRXtNlghWv-husw9hByGTp53_g0RxhmzoNc,5735
5
+ bisslog_flask/cli/__init__.py,sha256=Qd9zgdNKb6lAFb7Nsf8USrO_NNuemtOIfJAm8hOZXqc,3660
6
+ bisslog_flask/cli/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ bisslog_flask/cli/commands/build.py,sha256=QiXQvI3tHCS4i8Xbq6ucdx5lwkWg6yzsvQKqV6y4-p8,2339
8
+ bisslog_flask/cli/commands/run.py,sha256=6RDEDw8HrwDupii9e-O-Q2bfrIqGmDuMYa3wUvRCW5E,1953
9
+ bisslog_flask/initializer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ bisslog_flask/initializer/bisslog_flask_http_resolver.py,sha256=d-KFQwMXeRyq3_Cu5bxCF7CpnetfnKainChEbdxDk2c,6257
11
+ bisslog_flask/initializer/bisslog_flask_resolver.py,sha256=QWjft6HZbBplbP1vVMNoPhGoSZBJubAotwLR76HVttw,1708
12
+ bisslog_flask/initializer/bisslog_flask_ws_resolver.py,sha256=s-eDdk5HA6E_D8iZC6IN7RSW-96mzu8m8VGL3Xqm9PQ,2974
13
+ bisslog_flask/initializer/init_flask_app_manager.py,sha256=55lb2WoKBHyD2_XSO1svMLZY0tP-yIm8XKLOVZBIogk,5389
14
+ bisslog_flask/socket_helper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ bisslog_flask/socket_helper/socket_helper.py,sha256=HHENwYT-qdrJlwmGszYqFM1MA1g6naRurUp6sYCHRRQ,2967
16
+ bisslog_flask-0.0.2.dist-info/licenses/LICENSE,sha256=TSlM1hRIXc6yR3xpGzy2DMSSbds0svqHSetfNfQqCEk,1074
17
+ bisslog_flask-0.0.2.dist-info/METADATA,sha256=oKpJICdabwz2vtIG70DyJEQVZQTNksX-teABr-dz8KQ,4177
18
+ bisslog_flask-0.0.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
+ bisslog_flask-0.0.2.dist-info/entry_points.txt,sha256=A2_A5lZt973oUBpuOCC78aTm7dGyHk6cemnn5_jOXHw,57
20
+ bisslog_flask-0.0.2.dist-info/top_level.txt,sha256=Xk85d0SIhkUP1HjsXOtq2vlU7yQT3mFApyb5IVgtG6w,14
21
+ bisslog_flask-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bisslog_flask = bisslog_flask.cli:main
@@ -1,13 +0,0 @@
1
- bisslog_flask/__init__.py,sha256=BEf_UxFtcMfaM-Smh_bwc6Xn8pR8LcEjby3nCs0hdXE,758
2
- bisslog_flask/initializer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- bisslog_flask/initializer/bisslog_flask_http_resolver.py,sha256=d-KFQwMXeRyq3_Cu5bxCF7CpnetfnKainChEbdxDk2c,6257
4
- bisslog_flask/initializer/bisslog_flask_resolver.py,sha256=QWjft6HZbBplbP1vVMNoPhGoSZBJubAotwLR76HVttw,1708
5
- bisslog_flask/initializer/bisslog_flask_ws_resolver.py,sha256=s-eDdk5HA6E_D8iZC6IN7RSW-96mzu8m8VGL3Xqm9PQ,2974
6
- bisslog_flask/initializer/init_flask_app_manager.py,sha256=QzO1dae3YFap2VEXK3gSexLkdfBGaLWrHK732z5s0K0,4682
7
- bisslog_flask/socket_helper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- bisslog_flask/socket_helper/socket_helper.py,sha256=sR9xQSPWzijhPNRh8WRxDbzE7rqFqm4w0Vql4gBGiGU,3037
9
- bisslog_flask-0.0.1.dist-info/licenses/LICENSE,sha256=TSlM1hRIXc6yR3xpGzy2DMSSbds0svqHSetfNfQqCEk,1074
10
- bisslog_flask-0.0.1.dist-info/METADATA,sha256=w82no5oSrRtS7XEDT38gs6UYIrzyuBHK4eEJkpQptH0,3551
11
- bisslog_flask-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
- bisslog_flask-0.0.1.dist-info/top_level.txt,sha256=Xk85d0SIhkUP1HjsXOtq2vlU7yQT3mFApyb5IVgtG6w,14
13
- bisslog_flask-0.0.1.dist-info/RECORD,,