I have a toy REST application which is structured in a following way:
- client/
- css/
- js/
- index.html
- server/
- app.py
... some other files which I use in app.py
app.py
is a flask restful endpoint which looks like this:
app = flask.Flask('some-name')
# a lot of API end points, which look in this way
@app.route('/api/something', methods=['GET'])
def func_1():
...
and now I want to serve my static index html. So after looking at this, this and this, I thought that I would be able to serve it easily by adding the following lines:
@app.route('/')
def home():
# but neither with this line
return app.send_static_file('../client/index.html')
# nor with this
return flask.render_template(flask.url_for('static', filename='../client/index.html'))
I can not see my html file (logs tell me: 127.0.0.1 - - [some day] "GET / HTTP/1.1" 404 -
). I know that I can move index.html in the server folder but is there a way to serve it from where it is right now?
P.S. when I added app._static_folder = "../client/"
and changed my home function to return app.send_static_file('index.html')
I finally started to receive my html file, but all the css/js file that are inside html are returned with 404.
To reference the static files using the url_for() function, pass in the name of the directory – static in this case – and the keyword argument of filename= followed by your static file name. Flask automatically creates a static view that serves static files from a folder named static in your application's directory.
It turns out the official Flask docs specify that the static url path is configurable using the 'static_url_path' parameter to the Flask application initializer. to include the static_url_path set to something useful like /public will do the trick. And voila, problem solved!
Flask – Static Files Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application.
Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on.
When creating flask app, configure static_folder to your client folder.
from flask import Flask
app = Flask(__name__, static_folder="client")
Then you can access js and css on url http://localhost:5000/static/css/main.css
About your initial question. You can serve static html pages with flask like this:
@app.route('/<path:path>')
def serve_page(path):
return send_from_directory('client', path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With