【问题标题】:Is it possible to mount an instance of FastAPI onto a Flask application?是否可以将 FastAPI 的实例安装到 Flask 应用程序上?
【发布时间】:2021-12-28 11:13:41
【问题描述】:
我知道it's possible to mount an instance of flask on top of FastAPI。这意味着所有发往根 URL 的请求都由 FastAPI 处理,并且只有发往指定烧瓶 URL 的请求才会转发给它。
是否可以反过来这样做?我有一个用烧瓶构建的网站,我想向它添加一个 API 来管理来自另一个应用程序的数据库。 FastAPI 具有自动文档和验证功能,这让生活变得更加轻松。我想这样安装它的原因
如果没有,我可以用 uvicorn 单独托管它并将所有以 /api/ 开头的 URL 转发给它,并以某种方式返回它通过烧瓶返回的任何内容吗?
我在这里混合而不是单独运行它们的原因是我无法从烧瓶应用程序外部访问数据库。
【问题讨论】:
标签:
python
flask
flask-sqlalchemy
【解决方案1】:
我使用两个独立的 Flask 应用程序完成了这项工作(请参阅 here)。
它可以与 FastAPI 实例一起使用。
【解决方案2】:
经过一番修改,我想出了一个解决方案。
我现在将 flask 和 FastAPI 作为两个独立的应用程序运行。我添加了一条到 Flask 的路由,使它像 FastAPI 应用程序的代理一样:
API_URL = "http://127.0.0.1:8000/"
@views.route("/api/<path:rest>")
def api_redirect(rest):
return requests.get(f"{API_URL}{rest}").content
然后我使用 uvicorn main:app --root-path api/ 运行 FastAPI,以便前端知道在哪里可以找到 openapi.json 文件。
我通过添加以下代码解决了访问数据库时遇到的问题(由于不在会话中)。
engine = create_engine(DB_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
models.db.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/all-items", response_model=List[schemas.Item], tags=["items"])
def all_items(db: Session = Depends(get_db)):
return db.query(models.Item).all()
这会为每个 API 调用创建一个新会话,然后在调用完成后关闭它。