In a templates/index.html
file I can write
<link rel="stylesheet" type="text/css"
href={{ url_for('static', filename='css/main.css') }}>
and url_for
retrieves the CSS file from a static folder just fine (FWIW, notwithstanding that css/main.css
has a forward slash on Windows).
I would like to open a static file static/number.txt
, read one number from it, and display that number.
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def number():
filename = url_for('static', filename='txt/number.txt')
with open(filename) as f:
number = next(f)
return render_template('index.html', number=number)
if __name__ == '__main__':
app.run()
static/txt/number.txt
2345
templates/index.html
<body>
{{ number }}
</body>
For this simple example, I am not attempting to optimize by running Nginx
and IIUC this simple task requires neither send_from_directory()
nor os.getcwd()
. There is also no need to tinker with app.static_folder
nor to be worried about the folder separator by using os.join.path()
(I happen to be on Windows, but ideally this should be invisible in the code). There is also no need to modify the default static
folder.
The code above gives me
c:\read-static>python app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\anaconda3\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
...
File "app.py", line 10, in number
with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/static/txt/number.txt'
127.0.0.1 - "GET / HTTP/1.1" 500 -
What am I missing? Should I be using os.getcwd()
to read a static file in Flask? Something in relying on os.getcwd()
seems unpalatable/hackish.