Search code examples
flaskstatic-files

Can't get the right url_for static file in Flask locally


I have a web server that can do what I need, but for the purpose of developing the app I want some of my static files to be served locally. For example, I have /Desktop/project_folder/static/jsons/example.json. I try:

print(url_for('static', filename='jsons/example.json'))
/static/jsons/example.json

What I get is /static/jsons/example.json.

I try to set the static_path by:

app = Flask(__name__, static_folder='/Desktop/project_folder/static')
print(app.static_folder)
/Desktop/project_folder/static
url = url_for('static', filename='jsons/example.json')
print(url)
/static/jsons/example.json

I checked a few dozens similar questions here and they all suggest adjusting either static_folder or static_url_path but neither of those helps - I just start to get 404 errors on all other resources I have in my static folder. I also tried send_from_directory but what I get is werkzeug.wrappers.Response object and I can't get the data out of it.

UPDATE: I try to load this json with:

json_loaded = json.load(requests.get(url).text)

And get an error: MissingSchema: Invalid URL '/static/jsons/example.json’: No schema supplied.


Solution

  • You need to tell requests where the file lives. A path isn't enough. You also need to include a scheme and a domain, hostname, or IP address. Only the port is optional.

    requests.get('http://example.com/path/to/file')
    

    Since you are using url_for to generate the URL for you, you need to tell it to include this information for you.

    url_for('static', filename='jsons/example.json', _external=True)