backend.app

  1import os
  2import sys
  3from flask import Flask, render_template
  4from werkzeug.debug import DebuggedApplication
  5import logging
  6from flasgger import Swagger
  7
  8from backend.database.models import db
  9
 10
 11# Flask quickstart:
 12# https://flask.palletsprojects.com/en/3.0.x/quickstart/
 13# Flask factory pattern:
 14# https://flask.palletsprojects.com/en/3.0.x/tutorial/factory/
 15
 16def create_app():
 17    
 18    STATIC_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))
 19
 20
 21    # Create and configure the backend
 22    app = Flask(__name__,
 23                instance_relative_config=False,
 24                static_folder=STATIC_FOLDER,
 25                static_url_path='/static'
 26    )
 27
 28
 29    # Load config from file config.py
 30    app.config.from_pyfile('config.py')
 31    
 32    #setting log level
 33    app.logger.setLevel(logging.INFO)
 34
 35    # Keep static files path in backend config
 36    app.config["STATIC_FOLDER"] = STATIC_FOLDER
 37
 38
 39    # Enable debug mode - you will see beautiful error messages later :)
 40    # https://flask.palletsprojects.com/en/3.0.x/debugging/
 41    app.debug = True
 42    app.wsgi_app = DebuggedApplication(app.wsgi_app)
 43
 44
 45    # Ensure the instance folder exists - nothing interesting now
 46    try:
 47        os.makedirs(app.instance_path)
 48    except OSError:
 49        pass
 50    
 51
 52    # https://flask-sqlalchemy.palletsprojects.com/en/3.1.x/quickstart/#configure-the-extension
 53    # Allow database path override via FLASK_DB_PATH env or --db-path argument
 54    db_path = os.environ.get("FLASK_DB_PATH")
 55    if not db_path:
 56        # Check for --db-path in sys.argv
 57        for idx, arg in enumerate(sys.argv):
 58            if arg == "--db-path" and idx + 1 < len(sys.argv):
 59                db_path = sys.argv[idx + 1]
 60                break
 61    if not db_path:
 62        db_path = f"{os.getcwd()}/instance/database.sqlite"
 63
 64    app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
 65    db.init_app(app)
 66
 67    with app.app_context():
 68        db.create_all()
 69
 70    # Setup custom "Not found" page
 71    # https://flask.palletsprojects.com/en/3.0.x/errorhandling/#custom-error-pages
 72    @app.errorhandler(404)
 73    def page_not_found(e):
 74        return render_template('404.html'), 404
 75
 76    # Defining components
 77    from backend.components.camera_verification.verificationController import bp as bp_verification
 78    app.register_blueprint(bp_verification)
 79
 80    # Health check endpoint
 81    @app.route('/health')
 82    def health_check():
 83        return {"status": "ok", "service": "camera-verification-api"}, 200
 84
 85
 86    from backend.components.workers.workerController import bp as bp_workers
 87    app.register_blueprint(bp_workers)
 88
 89    from backend.components.reports.reportController import bp as bp_reports
 90    app.register_blueprint(bp_reports)
 91
 92    # --------- Swagger UI config -----------
 93    swagger_config = {
 94        "headers": [],
 95        "specs": [
 96            {
 97                "endpoint": 'apispec',
 98                "route": '/apispec.json',
 99                "rule_filter": lambda rule: True,  # Ważne: pozwala widzieć endpointy z blueprintów
100                "model_filter": lambda tag: True,
101            }
102        ],
103        "static_url_path": "/flasgger_static",
104        "swagger_ui": True,
105        "specs_route": "/apidocs/"  # Pod tym adresem będzie dokumentacja
106    }
107
108    template = {
109        "swagger": "2.0",
110        "info": {
111            "title": "API Documentation",
112            "description": "Flask project API Documentation",
113            "version": "1.0.0"
114        }
115    }
116
117    Swagger(app, config=swagger_config, template=template)
118
119    return app
def create_app():
 17def create_app():
 18    
 19    STATIC_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))
 20
 21
 22    # Create and configure the backend
 23    app = Flask(__name__,
 24                instance_relative_config=False,
 25                static_folder=STATIC_FOLDER,
 26                static_url_path='/static'
 27    )
 28
 29
 30    # Load config from file config.py
 31    app.config.from_pyfile('config.py')
 32    
 33    #setting log level
 34    app.logger.setLevel(logging.INFO)
 35
 36    # Keep static files path in backend config
 37    app.config["STATIC_FOLDER"] = STATIC_FOLDER
 38
 39
 40    # Enable debug mode - you will see beautiful error messages later :)
 41    # https://flask.palletsprojects.com/en/3.0.x/debugging/
 42    app.debug = True
 43    app.wsgi_app = DebuggedApplication(app.wsgi_app)
 44
 45
 46    # Ensure the instance folder exists - nothing interesting now
 47    try:
 48        os.makedirs(app.instance_path)
 49    except OSError:
 50        pass
 51    
 52
 53    # https://flask-sqlalchemy.palletsprojects.com/en/3.1.x/quickstart/#configure-the-extension
 54    # Allow database path override via FLASK_DB_PATH env or --db-path argument
 55    db_path = os.environ.get("FLASK_DB_PATH")
 56    if not db_path:
 57        # Check for --db-path in sys.argv
 58        for idx, arg in enumerate(sys.argv):
 59            if arg == "--db-path" and idx + 1 < len(sys.argv):
 60                db_path = sys.argv[idx + 1]
 61                break
 62    if not db_path:
 63        db_path = f"{os.getcwd()}/instance/database.sqlite"
 64
 65    app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
 66    db.init_app(app)
 67
 68    with app.app_context():
 69        db.create_all()
 70
 71    # Setup custom "Not found" page
 72    # https://flask.palletsprojects.com/en/3.0.x/errorhandling/#custom-error-pages
 73    @app.errorhandler(404)
 74    def page_not_found(e):
 75        return render_template('404.html'), 404
 76
 77    # Defining components
 78    from backend.components.camera_verification.verificationController import bp as bp_verification
 79    app.register_blueprint(bp_verification)
 80
 81    # Health check endpoint
 82    @app.route('/health')
 83    def health_check():
 84        return {"status": "ok", "service": "camera-verification-api"}, 200
 85
 86
 87    from backend.components.workers.workerController import bp as bp_workers
 88    app.register_blueprint(bp_workers)
 89
 90    from backend.components.reports.reportController import bp as bp_reports
 91    app.register_blueprint(bp_reports)
 92
 93    # --------- Swagger UI config -----------
 94    swagger_config = {
 95        "headers": [],
 96        "specs": [
 97            {
 98                "endpoint": 'apispec',
 99                "route": '/apispec.json',
100                "rule_filter": lambda rule: True,  # Ważne: pozwala widzieć endpointy z blueprintów
101                "model_filter": lambda tag: True,
102            }
103        ],
104        "static_url_path": "/flasgger_static",
105        "swagger_ui": True,
106        "specs_route": "/apidocs/"  # Pod tym adresem będzie dokumentacja
107    }
108
109    template = {
110        "swagger": "2.0",
111        "info": {
112            "title": "API Documentation",
113            "description": "Flask project API Documentation",
114            "version": "1.0.0"
115        }
116    }
117
118    Swagger(app, config=swagger_config, template=template)
119
120    return app