| Total Complexity | 4 |
| Total Lines | 71 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | # -*- coding: utf-8 -*- |
||
| 2 | # pylint: disable=R0903 |
||
| 3 | 1 | """ |
|
| 4 | This module contains functions and variables for initializing application and db |
||
| 5 | """ |
||
| 6 | |||
| 7 | 1 | import os |
|
| 8 | 1 | import logging |
|
| 9 | 1 | from flask import Flask |
|
| 10 | 1 | from flask_sqlalchemy import SQLAlchemy # type: ignore |
|
| 11 | |||
| 12 | 1 | __author__ = "torrua" |
|
| 13 | 1 | __copyright__ = "Copyright 2022, loglan_db project" |
|
| 14 | 1 | __email__ = "[email protected]" |
|
| 15 | |||
| 16 | 1 | db = SQLAlchemy() |
|
| 17 | 1 | log = logging.getLogger(__name__) |
|
| 18 | |||
| 19 | |||
| 20 | 1 | class CLIConfig: |
|
| 21 | """ |
||
| 22 | Configuration object for remote database |
||
| 23 | """ |
||
| 24 | 1 | SQLALCHEMY_DATABASE_URI = os.environ.get('LOD_DATABASE_URL', None) |
|
| 25 | 1 | SQLALCHEMY_TRACK_MODIFICATIONS = False |
|
| 26 | |||
| 27 | |||
| 28 | 1 | def create_app(config, database): |
|
| 29 | """ |
||
| 30 | Create app |
||
| 31 | """ |
||
| 32 | |||
| 33 | # app initialization |
||
| 34 | 1 | app = Flask(__name__) |
|
| 35 | |||
| 36 | 1 | app.config.from_object(config) |
|
| 37 | |||
| 38 | # db initialization |
||
| 39 | 1 | database.init_app(app) |
|
| 40 | |||
| 41 | # database.create_all(app=app) when use need to re-initialize db |
||
| 42 | 1 | return app |
|
| 43 | |||
| 44 | |||
| 45 | 1 | def app_lod(config_lod=CLIConfig, database=db): |
|
| 46 | """ |
||
| 47 | Create LOD app with specified Config |
||
| 48 | :param config_lod: Database Config |
||
| 49 | :param database: SQLAlchemy() Database |
||
| 50 | :return: flask.app.Flask |
||
| 51 | """ |
||
| 52 | 1 | return create_app(config=config_lod, database=database) |
|
| 53 | |||
| 54 | |||
| 55 | 1 | def run_with_context(function): |
|
| 56 | """Context Decorator""" |
||
| 57 | 1 | def wrapper(*args, **kwargs): |
|
| 58 | |||
| 59 | 1 | db_uri = os.environ.get('LOD_DATABASE_URL', None) |
|
| 60 | |||
| 61 | 1 | if not db_uri: |
|
| 62 | 1 | log.error("Please, specify 'LOD_DATABASE_URL' variable.") |
|
| 63 | 1 | return |
|
| 64 | |||
| 65 | 1 | context = app_lod().app_context() |
|
| 66 | 1 | context.push() |
|
| 67 | 1 | function(*args, **kwargs) |
|
| 68 | 1 | context.pop() |
|
| 69 | |||
| 70 | return wrapper |
||
| 71 |