English 中文(简体)
FastAPI - Mounting Flast App
  • 时间:2024-09-17

FastAPI - Mounting Flask App


Previous Page Next Page  

A WSGI apppcation written in Flask or Django framework can be wrapped in WSGIMiddleware and mounted it on a FastAPI app to make it ASGI comppant.

First install the Flask package in the current FastAPI environment.


pip3 install flask

The following code is a minimal Flask apppcation −


from flask import Flask
flask_app = Flask(__name__)
@flask_app.route("/")
def index_flask():
   return "Hello World from Flask!"

Then declare app as a FastAPI apppcation object and define an operation function for rendering Hello World message.


from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def index():
   return {"message": "Hello World from FastAPI!"}

Next, mount the flask apppcation as a sub apppcation of FastAPI main app using mount() method.


from fastapi.middleware.wsgi import WSGIMiddleware
app.mount("/flask", WSGIMiddleware(flask_app))

Run the Uvicorn development server.


uvicorn flaskapp:app –reload

The main FastAPI apppcation is available at the URL http://localhost:8000/ route.


{"message":"Hello World from FastAPI!"}

The Flask sub apppcation is mounted at the URL http://localhost:8000/flask.


Hello World from Flask!
Advertisements