Run NPM builds from Flask
I
have a React frontend and I want to serve on the same source as my python backend API. I’m trying to use Flask for this, but I’m having an issue where Flask can’t find my static files.
My frontend build was built using npm run build
in saas_frontend
Here is my file structure :
├── main.py
├── requirements.txt
├── run.sh
├── saas_backend
├── saas_frontend
Flask runs from main.py
and serves my frontend in saas_frontend/build
:
├── asset-manifest.json
├── favicon.ico
├── index.html
├── manifest.json
├── service-worker.js
└── static
├── css
│ ├── main.096c9e23.css
│ └── main.096c9e23.css.map
├── js
│ ├── main.8949f17a.js
│ └── main.8949f17a.js.map
└── media
├── delta.56f5d855.csv
└── logo.e233ff84.png
I declared the new template path and static path in the main.py
as follows:
import os
from flask import Flask, render_template
template_dir = os.path.abspath('saas_frontend/build/')
static_dir = os.path.abspath('saas_frontend/build/static')
app = Flask(__name__, static_path=static_dir, template_folder=template_dir)
@app.route('/')
def index():
print template_dir
print static_dir
return render_template('index.html')
But Flask still can’t serve my static file, I’ll take it as output…
127.0.0.1 - - [21/Jul/2017 12:13:14] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Jul/2017 12:13:14] "GET /static/css/main.096c9e23.css HTTP/1.1" 404 -
127.0.0.1 - - [21/Jul/2017 12:13:14] "GET /static/js/main.8949f17a.js HTTP/1.1" 404 -
127.0.0.1 - - [21/Jul/2017 12:13:14] "GET /static/css/main.096c9e23.css HTTP/1.1" 404 -
127.0.0.1 - - [21/Jul/2017 12:13:14] "GET /static/js/main.8949f17a.js HTTP/1.1" 404 -
Is there anything I should do differently? How does Flask parse the correct file with the path in the error message, but can’t provide it to the browser at all?
Thanks!!
Solution
I solved my problem by using symbolic links to the corresponding files and directories.
In my build script, I’ll include:
ln -s saas_frontend/build/static static
ln -s saas_frontend/build templates
Now everything is normal!