[Python] How to route from Flask to React with specific path

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have a project in flask split into blueprints for each app. I want to incrementally rewrite each blueprint's template in react, however I need all of them to be in one react project.

    Is there a way I can set this up where it will try to route to the react SPA, if a route doesn't exist there then it loads the flask template?

    I'm thinking create a blueprint under /app that will serve the index.html but how would I get /app/user-page to route to the correct page with react router?

    Here's what I currently have, is there a way to take the path and send that to react router somehow?

    react_app_bp = Blueprint(
    "react_app", __name__, static_folder="static", template_folder="templates"
    )


    # Serve static assets (JS, CSS)
    @react_app_bp.route("/assets/<path:filename>")
    def serve_assets(filename):
    return send_from_directory(os.path.join(react_app_bp.static_folder, "assets"), filename)

    # Serve the React app's entry point
    @react_app_bp.route("/", defaults={"path": ""})
    @react_app_bp.route("/<path:path>")
    @login_required
    def serve_react_app(path):
    build_dir = os.path.join(os.path.dirname(__file__), "static")

    if path and os.path.exists(os.path.join(build_dir, path)):
    return send_from_directory(build_dir, path)

    return send_from_directory(build_dir, "index.html")

    Continue reading...

Compartilhe esta Página