Including WSGI - Flask, Django, others

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can mount WSGI applications as you saw with Sub Applications - Mounts, Behind a Proxy.

For that, you can use the WSGIMiddleware and use it to wrap your WSGI application, for example, Flask, Django, etc.

Using WSGIMiddleware

You need to import WSGIMiddleware.

Then wrap the WSGI (e.g. Flask) app with the middleware.

And then mount that under a path.

  1. from fastapi import FastAPI
  2. from fastapi.middleware.wsgi import WSGIMiddleware
  3. from flask import Flask, escape, request
  4. flask_app = Flask(__name__)
  5. @flask_app.route("/")
  6. def flask_main():
  7. name = request.args.get("name", "World")
  8. return f"Hello, {escape(name)} from Flask!"
  9. app = FastAPI()
  10. @app.get("/v2")
  11. def read_main():
  12. return {"message": "Hello World"}
  13. app.mount("/v1", WSGIMiddleware(flask_app))

Check it

Now, every request under the path /v1/ will be handled by the Flask application.

And the rest will be handled by FastAPI.

If you run it with Uvicorn and go to http://localhost:8000/v1/ you will see the response from Flask:

  1. Hello, World from Flask!

And if you go to http://localhost:8000/v2 you will see the response from FastAPI:

  1. {
  2. "message": "Hello World"
  3. }