Skip to content

Latest commit

 

History

History
76 lines (50 loc) · 1.8 KB

File metadata and controls

76 lines (50 loc) · 1.8 KB

Flask to FastAPI Migration Example

Documentation

This example demonstrates how to use Codegen to automatically migrate a Flask application to FastAPI. For a complete walkthrough, check out our tutorial.

What This Example Does

The migration script handles four key transformations:

  1. Updates Imports and Initialization

    # From:
    from flask import Flask
    
    app = Flask(__name__)
    
    # To:
    from fastapi import FastAPI
    
    app = FastAPI()
  2. Converts Route Decorators

    # From:
    @app.route("/users", methods=["POST"])
    
    # To:
    @app.post("/users")
  3. Sets Up Static File Handling

    # Adds:
    from fastapi.staticfiles import StaticFiles
    
    app.mount("/static", StaticFiles(directory="static"), name="static")
  4. Updates Template Rendering

    # From:
    return render_template("users.html", users=users)
    
    # To:
    return Jinja2Templates(directory="templates").TemplateResponse("users.html", context={"users": users}, request=request)

Running the Example

# Install Codegen
pip install codegen

# Run the migration
python run.py

The script will process all Python files in the repo-before directory and apply the transformations in the correct order.

Understanding the Code

  • run.py - The migration script
  • input_repo/ - Sample Flask application to migrate

Learn More