FastAPI - Mounting a Flask App
A WSGI application written in Flask or Django framework can be wrapped in WSGIMiddleware and mounted it on a FastAPI app to make it ASGI compliant.
First install the Flask package in the current FastAPI environment.
Installing Flask
pip3 install flask
Example - A Flask Based Application
The following code is a minimal Flask application −
main.py
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 application 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 application as a sub application of FastAPI main app using mount() method.
from fastapi.middleware.wsgi import WSGIMiddleware
app.mount("/flask", WSGIMiddleware(flask_app))
Output
Run the Uvicorn development server.
uvicorn flaskapp:app reload
The main FastAPI application is available at the URL http://localhost:8000/ route.
{"message":"Hello World from FastAPI!"}
The Flask sub application is mounted at the URL http://localhost:8000/flask.
Hello World from Flask!
Advertisements