Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve React production App (local server) through Flask-Python

I'm producing an application with these two technologies: React-app & Flask-Python. Its intended to run a react client to represent data received from Flask-server. The flask server and react client are on the same machine and communicate trough sockets (SocketIO).

In Dev mode, in order to run the application, I have to run the react server with npm start (node) and the flask server with python.

In production mode, after the react server is built, I have to serve the build folder with the serve option available on Node. Otherwise the app will not work properly (I think its because I use react-router, and when I go to another place of my react app, the browser cannot find the URL's specified. When serving the build folder with serve option of Node, no problem shows up).

So, my question is: Can I serve the build folder of my react application with flask instead of serve option of node? I want to do this, in order to eliminate the Node.js dependency so if I want to run my application on another machine, I will not have to install node.

like image 710
Ricardo Goncalves Avatar asked Apr 16 '18 13:04

Ricardo Goncalves


2 Answers

Yes it's possible to do it in flask with static folder/files. You need to create a folder which is called static in your project. Imagine this folder structure:

├── server/
└── static/
    ├── css/
    ├── dist/
    ├── images/
    └── js/
        index.html

For your react app the only thing you need do is to build npm run build.

In flask you should set this static folder in order to be used. You need in a simplified version this:

# server.py
from flask import Flask, render_template

app = Flask(__name__, static_folder="../static/dist", template_folder="../static")

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/hello")
def hello():
    return "Hello World!”

if __name__ == "__main__":
    app.run()

So the root path / will show react. The /hello path will show the response from flask.

like image 57
Spiros I. Economakis Avatar answered Sep 17 '22 18:09

Spiros I. Economakis


So i got this working by doing this:

-Build my react app with

npm run build

my app structure right now is:

├── server-flask/
    ├── ...
    ├── static/
├── react-app/
      ├── ...
      ├── build/

-Copied the content of build folder to /server-flask/static.

-And my flask code looked like this:

from flask import Flask, send_from_directory
import os

app = Flask(__name__, static_folder="/static")


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

if __name__ == "__main__":
    app.run()
like image 36
Ricardo Goncalves Avatar answered Sep 20 '22 18:09

Ricardo Goncalves