-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrun.py
More file actions
131 lines (104 loc) Β· 5.01 KB
/
run.py
File metadata and controls
131 lines (104 loc) Β· 5.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from codegen import Codebase
# Initialize codebase
codebase = Codebase("./")
# Define the target directory
TARGET_DIR = "repo-before"
def update_flask_imports_and_init(file):
"""Update Flask imports and initialization to FastAPI"""
print(f"π Processing file: {file.filepath}")
# Update imports
for imp in file.imports:
if imp.name == "Flask":
print(" π¦ Updating import: Flask -> FastAPI")
imp.set_name("FastAPI")
elif imp.symbol_name == "flask":
print(" π¦ Updating import module: flask -> fastapi")
imp.set_import_module("fastapi")
# Update Flask initialization and remove __name__
for call in file.function_calls:
if call.name == "Flask":
print(" π§ Updating function call: Flask -> FastAPI")
call.set_name("FastAPI")
if len(call.args) > 0 and call.args[0].value == "__name__":
print(" ποΈ Removing __name__ argument from FastAPI initialization")
call.args[0].remove()
def update_route_decorators(file):
"""Convert Flask route decorators to FastAPI style"""
print(f"\nπ Processing file: {file.filepath}")
for function in file.functions:
for decorator in function.decorators:
if "@app.route" in decorator.source:
route = decorator.source.split('"')[1]
method = "get"
if "methods=" in decorator.source:
methods = decorator.source.split("methods=")[1].split("]")[0].strip().lower().replace("'", "").replace('"', "")
if "post" in methods:
method = "post"
elif "put" in methods:
method = "put"
elif "delete" in methods:
method = "delete"
new_decorator = f'@app.{method}("{route}")'
decorator.edit(new_decorator)
print(f"π Updated decorator for function '{function.name}': {new_decorator}")
def setup_static_files(file):
"""Add static file handling for FastAPI"""
print(f"π Processing file: {file.filepath}")
# Add import for StaticFiles
file.add_import_from_import_string("from fastapi.staticfiles import StaticFiles")
print("β
Added import: from fastapi.staticfiles import StaticFiles")
# Add app.mount for static file handling
file.add_symbol_from_source('app.mount("/static", StaticFiles(directory="static"), name="static")')
print("β
Added app.mount for static file handling")
def update_jinja2_syntax(file):
"""Update Jinja2 template handling for FastAPI"""
print(f"\nπ Processing: {file.filepath}")
# Update url_for calls
for func_call in file.function_calls:
if func_call.name == "url_for" and func_call.args:
arg_value = func_call.args[0].value
if arg_value and arg_value[0] != "'" and arg_value[0] != '"':
func_call.args[0].set_value(f"'{arg_value}'")
# Update extends and include statements
for tag in ["extends", "include"]:
for statement in file.search(f"{{% {tag} "):
source = statement.source.strip()
if source[-1] != "'":
if source[-1] == '"':
source = source[:-1] + "'"
else:
source += "'"
new_source = f"{{% {tag} '{source[len(f'{{% {tag} ') :]}"
statement.edit(new_source)
# Update render_template calls
for func_call in file.function_calls:
if func_call.name == "render_template":
func_call.set_name("Jinja2Templates(directory='templates').TemplateResponse")
if len(func_call.args) > 1:
context_arg = ", ".join(f"{arg.name}={arg.value}" for arg in func_call.args[1:])
func_call.set_kwarg("context", f"{'{'}{context_arg}{'}'}")
func_call.set_kwarg("request", "request")
def main():
"""Main function to run the Flask to FastAPI migration"""
print("π Starting Flask to FastAPI migration...\n")
# Process each file in the target directory
for file in codebase.files:
if TARGET_DIR in file.filepath:
# Step 1: Update Flask imports and initialization
print("\nπ Step 1: Updating Flask imports and initialization...")
update_flask_imports_and_init(file)
# Step 2: Update route decorators
print("\nπ Step 2: Converting route decorators...")
update_route_decorators(file)
# Step 3: Setup static file handling
print("\nπ Step 3: Setting up static file handling...")
setup_static_files(file)
# Step 4: Update Jinja2 template handling
print("\nπ Step 4: Updating Jinja2 template handling...")
update_jinja2_syntax(file)
# Commit all changes
print("\nπΎ Committing changes...")
codebase.commit()
print("β
Flask to FastAPI migration completed successfully!")
if __name__ == "__main__":
main()