Share the same models and database session between Flask and FastAPI application

Viewed 263

I started for developing a project for an IoT application in Flask. This application has an API blueprint which has been growing a lot and now I'm trying to migrate the API to FastAPI. My project follows this structure:

api (FastAPI application)
     __init__.py (where I create the FastAPI app)
application (Flask application)
     __init__.py (where I create the Flask app)
models (SQL alchemy models that I want to share between both applications)
wsgi.py (I use multiprocessing to launch to separate processes, one for the Flask App and another for Fast Api)

The Flask module is running well and the FastApi one is running too. However, I can't use my models in the FastAPI routers since I'm not initializing the db correctly in this. I need to create something that let me share the session between the FastAPI and Flask modules.

I let you with my __init__.py of both modules:

Flask:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def create_app():
   """Initialize the core application."""
   app = Flask(__name__, instance_relative_config=False)
   # The following line loads the configurations from Config file
   app.config.from_object('config.DevelopmentConfig')
   db.init_app(app)

   with app.app_context():
      # Import parts of our application
      from application.blueprints.oauth.routes import auth as auth_blueprint
      app.register_blueprint(auth_blueprint)
    
      ....

      db.create_all()
      return app

FastAPI:

from fastapi import FastAPI, APIRouter
from fastapi_sqlalchemy import DBSessionMiddleware  # middleware helper
from fastapi_sqlalchemy import db
from .controllers.system import *


def create_app():
   """Initialize the core application."""
   app = FastAPI(debug=True)

   app.add_middleware(DBSessionMiddleware, db_url="sqlite:///../database.db")

   app.include_router(router=router)

   return app

How could I make this work?

Best regards,

0 Answers
Related