Reputation: 988
I am pretty new in using flask and have a basic question: How to provide access to an HTML that is rendered using flask access to static files (such as images). Here my toy example:
I would like to render logo.svg on a website. The Project is structured as
Project
|
+ -- static
|
+ -- logo.svg
+ -- templates
|
+ -- test.html
+ -- run_flask.py
test.html looks as follows
<!DOCTYPE>
<html>
<head>
<title>demo</title>
<style>
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<img src="./static/logo.svg" id="logo">
</body>
</html>
and my run_flask-py script contains:
import flask
from flask import render_template, send_from_directory
from flask_cors import CORS
app = flask.Flask(__name__, static_url_path='')
CORS(app)
app.config["DEBUG"] = True
@app.route('/<string:page_name>/')
def render_static(page_name):
return render_template('%s.html' % page_name)
app.run(port=5001)
When a now run the script, the console output is:
Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
So far so good, but in chrome, http://127.0.0.1:5001/test/ looks like:
I already looked at How to serve static files in Flask as the problem sounds similar. But I am actually completed confused about how the suggested send_from_directory can help me here.
Can somebody help?
Upvotes: 1
Views: 2572
Reputation: 344
try with
<img src="../static/logo.svg" id="logo">
instead of
<img src="./static/logo.svg" id="logo">
the ..
points it to the parent directory and the /static enters into the static directory.
Upvotes: 0
Reputation: 7621
You ought to remove the static_url_path
argument when you initialise the app:
app = flask.Flask(__name__)
By default flask will look in the subdirectory static/
for any static files. Your directory structure meets this requirement.
As @roganjosh comments, this should then work in the template with:
<img src="{{ url_for('static', filename='logo.svg') }}" id="logo">
As a debug step, you could load http://127.0.0.1:5001/static/logo.svg
in the browser, and this should display correctly.
UPDATE: re. comment
So I guess an empty string defaults to the current app directory or would you need
/
for that
Always good to investigate the actual source code:
:param static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the `static_folder` folder. :param static_folder: the folder with static files that should be served at `static_url_path`. Defaults to the ``'static'`` folder in the root path of the application.
What you were probably looking for was static_folder
which controls the server based directory. static_url_path
effects the URL path which static files are available on the frontend.
Definately easier to just stick with the defaults here, and define neither.
Upvotes: 1