![](/img/trans.png)
[英]Store references to Dask Futures in a Flask/FastAPI Application
[英]Is it possible to mount an instance of FastAPI onto a Flask application?
我知道可以在 FastAPI 之上安装 flask 的实例。 这意味着所有发往根 URL 的请求都由 FastAPI 处理,只有发往指定 flask URL 的请求被转发给它。 是否可以反过来这样做? 我有一个使用 flask 构建的网站,我想在其中添加一个 API 以从另一个应用程序管理数据库。 FastAPI 具有自动文档和验证功能,这让生活变得更加轻松。 我想以这种方式安装它的原因
如果没有,我可以使用 uvicorn 单独托管它并将所有以 /api/ 开头的 URL 转发给它,并以某种方式返回它通过 flask 返回的任何内容吗?
我在这里混合而不是单独运行它们的原因是我无法从 flask 应用程序外部访问数据库。
我已经使用两个单独的 Flask 应用程序完成了此操作(请参见此处)。
它可以与 FastAPI 实例一起使用。
经过一番折腾,我想出了一个解决方案。
我现在将 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 调用创建一个新的 session,然后在调用完成后将其关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.