This example demonstrates how to use Codegen to automatically migrate a Flask application to FastAPI. For a complete walkthrough, check out our tutorial.
The migration script handles four key transformations:
-
Updates Imports and Initialization
# From: from flask import Flask app = Flask(__name__) # To: from fastapi import FastAPI app = FastAPI()
-
Converts Route Decorators
# From: @app.route("/users", methods=["POST"]) # To: @app.post("/users")
-
Sets Up Static File Handling
# Adds: from fastapi.staticfiles import StaticFiles app.mount("/static", StaticFiles(directory="static"), name="static")
-
Updates Template Rendering
# From: return render_template("users.html", users=users) # To: return Jinja2Templates(directory="templates").TemplateResponse("users.html", context={"users": users}, request=request)
# Install Codegen
pip install codegen
# Run the migration
python run.pyThe script will process all Python files in the repo-before directory and apply the transformations in the correct order.
run.py- The migration scriptinput_repo/- Sample Flask application to migrate