最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to route from Flask to React with specific path - Stack Overflow

programmeradmin0浏览0评论

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")

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")
Share Improve this question asked Mar 4 at 0:02 user29698336user29698336 1
Add a comment  | 

2 Answers 2

Reset to default 0

You could create completely barebones routes in the react app which would redirect to another port/domain which would host the Flask server.

With React app as the main domain, you would go to e.g. example/login and if login is only in the Flask, you would create a React route with just a redirect to e.g. flask.example/login.

I'm sure it's possible somehow to host two servers on the same domain, but it seems incredibly complicated for a small gain I do not see at the moment.

P.S. you can of course also do a redirect in Flask to the React app

To route from Flask to React with specific paths while allowing for incremental rewriting of your Flask blueprints, you can implement a solution that combines Flask's routing with React Router. Here's how you can modify your current setup to achieve this:

Update your Flask backend:

from flask import Flask, send_from_directory, jsonify
from flask_cors import CORS

app = Flask(__name__, static_folder='react_app/build')
CORS(app)

# Serve React App
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists(app.static_folder + '/' + path):
        return send_from_directory(app.static_folder, path)
    else:
        return send_from_directory(app.static_folder, 'index.html')

# API routes
@app.route('/api/some-endpoint')
def some_endpoint():
    return jsonify({"message": "This is an API endpoint"})

# Add more API routes as needed

if __name__ == '__main__':
    app.run(use_reloader=True, port=5000, threaded=True)





Set up your React app:

In your React app, use React Router to handle client-side routing. Here's a basic example:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import UserPage from './components/UserPage';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/app/user-page" component={UserPage} />
        {/* Add more routes as needed */}
      </Switch>
    </Router>
  );
}

export default App;

Configure your build process:

Make sure your React app is built and the output is placed in the react_app/build directory (or wherever your static_folder is set in Flask).

Handle API requests:

In your React components, make API calls to your Flask backend using the /api prefix. For example:

import React, { useEffect, useState } from 'react';

function UserPage() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/some-endpoint')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      <h1>User Page</h1>
      {data && <p>{data.message}</p>}
    </div>
  );
}

export default UserPage;
发布评论

评论列表(0)

  1. 暂无评论