-
Notifications
You must be signed in to change notification settings - Fork 45
flask to fastapi conversion #188
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,84 +1,84 @@ | ||
| """ | ||
| Flask Server! | ||
| FastAPI Server! | ||
| """ | ||
|
|
||
| import logging | ||
| import subprocess | ||
| import sys | ||
| import urllib.parse | ||
| from pathlib import Path | ||
|
|
||
| from flask import ( | ||
| Flask, | ||
| render_template, | ||
| request, | ||
| send_file, | ||
| send_from_directory, | ||
| ) | ||
| from flask_cors import CORS | ||
| import uvicorn | ||
| from fastapi import FastAPI, HTTPException, Request | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from fastapi.responses import FileResponse, PlainTextResponse | ||
| from fastapi.templating import Jinja2Templates | ||
|
|
||
| from src.settings import ServerSettings | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| BASE_DIR = Path(__file__).resolve().parent.parent | ||
| TEMPLATES_DIR = BASE_DIR / "src" / "templates" | ||
| CLI_PATH = BASE_DIR / "src" / "cli.py" | ||
|
|
||
| templates = Jinja2Templates(directory=str(TEMPLATES_DIR)) | ||
|
|
||
|
|
||
| def create_app(env): | ||
| """ | ||
| Application factory function | ||
| """ | ||
| app = Flask(__name__) | ||
| CORS(app) | ||
| app = FastAPI() | ||
|
|
||
| # define which "origins" (frontend urls) can talk to this api | ||
| origins = ["http://localhost:8501", "http://127.0.0.1:8501"] | ||
|
|
||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=origins, | ||
| allow_credentials=True, | ||
| allow_methods=["GET"], | ||
| allow_headers=["*"], | ||
| ) | ||
|
|
||
| @app.route("/help") | ||
| def serve_help(): | ||
| @app.get("/help") | ||
| async def serve_help(): | ||
| """Serves the help.txt file.""" | ||
| return send_from_directory( | ||
| Path(__file__).resolve().parents[1], "help.txt" | ||
| ) | ||
|
|
||
| @app.route("/home") | ||
| def serve_index(): | ||
| """Serves index.html.""" | ||
| return render_template("index.html", env_vars=env.model_dump()) | ||
|
|
||
| @app.route("/script.js") | ||
| def serve_script(): | ||
| """Serves the frontend JavaScript.""" | ||
| return send_file("static/script.js") | ||
|
|
||
| @app.route("/") | ||
| def default_route(): | ||
| HELP_FILE_PATH = BASE_DIR / "help.txt" | ||
| return FileResponse(path=HELP_FILE_PATH, media_type="text/plain") | ||
|
|
||
| @app.get("/", response_class=PlainTextResponse) | ||
| async def default_route(request: Request): | ||
| """Serves the surf report.""" | ||
| query_parameters = urllib.parse.parse_qsl( | ||
| request.query_string.decode(), keep_blank_values=True | ||
| ) | ||
| parsed_parameters = [ | ||
| f"{key}={value}" if value else key | ||
| for key, value in query_parameters | ||
| for key, value in request.query_params.items() | ||
|
Comment on lines
+50
to
+55
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue (bug_risk): Query parameter handling now drops duplicate keys compared to the previous implementation.
|
||
| ] | ||
| args = ",".join(parsed_parameters) | ||
|
|
||
| try: | ||
| result = subprocess.run( | ||
| [sys.executable, Path("src") / "cli.py", args], | ||
| [sys.executable, str(CLI_PATH), args], | ||
| capture_output=True, | ||
| text=True, | ||
| check=True, | ||
|
Comment on lines
60
to
64
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. security (python.lang.security.audit.dangerous-subprocess-use-audit): Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'. Source: opengrep |
||
| ) | ||
| return result.stdout | ||
| except subprocess.CalledProcessError as e: | ||
| logger.error("Subprocess error: %s", e.stderr) | ||
| raise | ||
| raise HTTPException(status_code=500, detail="Internal CLI Error") | ||
|
|
||
| return app | ||
|
|
||
|
|
||
| env = ServerSettings() | ||
| app = create_app(env) | ||
|
|
||
| if __name__ == "__main__": # pragma: no cover | ||
| logging.basicConfig( | ||
| level=logging.INFO, | ||
| format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", | ||
| datefmt="%Y-%m-%d %H:%M:%S", | ||
| ) | ||
| env = ServerSettings() | ||
| app = create_app(env) | ||
| app.run(host="0.0.0.0", port=env.PORT, debug=env.DEBUG) | ||
|
|
||
| uvicorn.run(app, host=str(env.IP_ADDRESS), port=env.PORT) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -86,8 +86,8 @@ | |
| </div> | ||
| </div> | ||
| <script> | ||
| // load .env variables from Flask server | ||
| const env = {{ env_vars|tojson }}; | ||
|
Comment on lines
-89
to
-90
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🚨 issue (security): Switching from
|
||
| // load .env variables from FastAPI server | ||
| const env = {{ env_vars | safe }}; | ||
| </script> | ||
| <script src="{{ url_for('serve_script') }}"></script> | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue (bug_risk): Template still references This reference will now fail at render time, since the Flask |
||
| </body> | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (bug_risk): CORS is restricted to GET only, which may be too tight if non-GET endpoints are introduced.
Compared to the previous
CORS(app)usage, this configuration will cause any future POST/PUT/DELETE routes to fail CORS preflight even though FastAPI accepts them. If you expect to add non-GET endpoints, consider either listing those methods explicitly or using a broader set of standard methods to avoid hard-to-diagnose frontend errors.