简体   繁体   English

是否可以将 FastAPI 实例安装到 Flask 应用程序上?

[英]Is it possible to mount an instance of FastAPI onto a Flask application?

I know that it's possible to mount an instance of flask on top of FastAPI .我知道可以在 FastAPI 之上安装 flask 的实例 This means that all requests going to the root URL are handled by FastAPI and only the requests to the specified flask URL are forwarded to it.这意味着所有发往根 URL 的请求都由 FastAPI 处理,只有发往指定 flask URL 的请求被转发给它。 Is it possible to do this the other way around?是否可以反过来这样做? I have a website that I've built with flask and I'd like to add an API to it to manage the database from another app.我有一个使用 flask 构建的网站,我想在其中添加一个 API 以从另一个应用程序管理数据库。 FastAPI has automatic documentation and validation which makes life a lot easier. FastAPI 具有自动文档和验证功能,这让生活变得更加轻松。 The reason I want to mount it this way round我想以这种方式安装它的原因

If not, can I host it separately with uvicorn and forward all URLs starting with /api/ to it and somehow return whatever it returns through flask?如果没有,我可以使用 uvicorn 单独托管它并将所有以 /api/ 开头的 URL 转发给它,并以某种方式返回它通过 flask 返回的任何内容吗?

The reason I'm mixing things up here rather than running them separately is that I'm having trouble accessing the database from outside of the flask application.我在这里混合而不是单独运行它们的原因是我无法从 flask 应用程序外部访问数据库。

I've done this with two separate Flask applications (see here ).我已经使用两个单独的 Flask 应用程序完成了此操作(请参见此处)。

It may work with a FastAPI instance.它可以与 FastAPI 实例一起使用。

After some tinkering, I figured out a solution.经过一番折腾,我想出了一个解决方案。

I am now running flask and FastAPI as two separate applications.我现在将 flask 和 FastAPI 作为两个单独的应用程序运行。 I have added a route to flask that makes it act like a proxy for the FastAPI app:我添加了一条到 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

I then ran FastAPI with uvicorn main:app --root-path api/ so that the frontend knows where to find the openapi.json file.然后我使用uvicorn main:app --root-path api/运行 FastAPI,以便前端知道在哪里可以找到openapi.json文件。

I solved the issue I was having with accessing the database (due to not being in a session) by adding the following code.我通过添加以下代码解决了访问数据库时遇到的问题(由于不在会话中)。

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()

This creates a new session for each API call and then closes it when the call has been made.这会为每个 API 调用创建一个新的 session,然后在调用完成后将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM