Running NPM Build from Flask

2020-06-07 01:47发布

问题:

I have a React front end that I would like to serve on the same origin as my python backend API. I'm trying to use Flask for this, but I'm running into an issue with Flask not finding my static files.

My front end build is generated with npm run build in saas_frontend

Here is what my file structure looks like:

    ├── main.py
    ├── requirements.txt
    ├── run.sh
    ├── saas_backend
    ├── saas_frontend

Flask is running from main.py and serving my front end 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 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 is still unable to serve my static files and I get this as the 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 be doing differently? How can Flask resolve the right file with path in the error message but be completely unable to serve it to the browser?

Thanks!!

回答1:

I fixed my issue by using symlinks to the appropriate files and directories.

In my build script I will include:

ln -s saas_frontend/build/static static
ln -s saas_frontend/build templates

Everything works as expected now!