You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Flask-Python本地部署React生产环境应用?

Solution for React + Flask-SocketIO App (Development & Production Deployment)

I’ve worked through similar setups before—let’s break this down into clear, actionable steps for both modes:


Development Mode Setup

In dev, we’ll run React and Flask as separate servers (since React’s dev server provides hot reloading). The key here is handling cross-origin requests and SocketIO connections correctly.

Step 1: Configure Flask Server

First, install the required packages:

pip install flask flask-socketio flask-cors

Create your Flask app (e.g., app.py):

from flask import Flask
from flask_socketio import SocketIO, emit
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Allow cross-origin requests from React's dev server
socketio = SocketIO(app, cors_allowed_origins="*")  # Enable SocketIO CORS

# Example SocketIO event handler
@socketio.on('connect')
def handle_client_connect():
    print("New client connected")
    emit('server_message', {'content': 'Welcome to the Flask SocketIO server!'})

if __name__ == '__main__':
    socketio.run(app, debug=True, port=5000)  # Runs on localhost:5000

Step 2: Configure React Client

Install the SocketIO client for React:

npm install socket.io-client

Add SocketIO logic to your React component (e.g., App.jsx):

import { useEffect, useState } from 'react';
import io from 'socket.io-client';

// Connect to Flask's SocketIO server (dev port 5000)
const socket = io('http://localhost:5000');

function App() {
  const [serverMessage, setServerMessage] = useState('');

  useEffect(() => {
    // Listen for messages from the server
    socket.on('server_message', (data) => {
      setServerMessage(data.content);
    });

    // Cleanup on component unmount
    return () => socket.disconnect();
  }, []);

  return (
    <div className="App">
      <h2>Flask SocketIO Message:</h2>
      <p>{serverMessage}</p>
    </div>
  );
}

export default App;

Run Dev Servers

  • Start Flask: python app.py
  • Start React: npm start (runs on localhost:3000 by default)

Production Mode Deployment

In production, we’ll build React’s optimized static files and serve them directly from Flask—so only one server runs.

Step 1: Build React Production Assets

In your React project directory, run:

npm run build

This creates a build folder containing all optimized HTML/CSS/JS files.

Step 2: Integrate React Build with Flask

Move the build folder into your Flask project root (or update the path in the code below to point to it).

Update your Flask app (app.py) to serve React’s static files and handle React Router (if you’re using it):

from flask import Flask, send_from_directory
from flask_socketio import SocketIO, emit
import os

# Point Flask to React's build folder as static assets
app = Flask(__name__, static_folder='build', static_url_path='/')
socketio = SocketIO(app)

# Serve React's index.html for the root route
@app.route('/')
def serve_home():
    return send_from_directory(app.static_folder, 'index.html')

# Catch-all route for React Router (handles all non-API routes)
@app.route('/<path:path>')
def catch_all_routes(path):
    return send_from_directory(app.static_folder, 'index.html')

# Keep your existing SocketIO handlers
@socketio.on('connect')
def handle_client_connect():
    print("Production client connected")
    emit('server_message', {'content': 'Hello from production!'})

if __name__ == '__main__':
    # Use eventlet for production (install first: pip install eventlet)
    socketio.run(app, host='0.0.0.0', port=5000, debug=False)

Update React SocketIO Connection

In production, the React app runs on the same domain as Flask, so simplify the SocketIO connection in your React component:

const socket = io(); // Automatically connects to the current origin

Run Production Server

Install the production-ready async server for Flask-SocketIO:

pip install eventlet

Start the Flask server:

python app.py

Your app will now be accessible at http://localhost:5000, serving both React’s frontend and Flask’s SocketIO backend.


内容的提问来源于stack exchange,提问作者Ricardo Goncalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:11:23