简体   繁体   中英

Serving static json data to flask

I have json data in demo_data.json that I'd like to bring into a Flask app. I'm receiving a 404 on the file which I've placed in the static directory, my code is below, thanks for any thoughts in advance:

from flask import Flask, render_template
from flask import url_for

app = Flask(__name__, static_url_path='/static/')
@app.route('/')
def home():
    return render_template('home.html')
@app.route('/welcome')
def welcome():
    return render_template('welcome.html')
if __name__ == '__main__':
    app.run()
    return send_from_directory('/static', 'demo_data.json')

It looks like you have a trailing slash on your static_url_path. Removing the extra character resolved the issue. Also note the removed last line. The return call wasn't necessary and the function call after the return was a syntax error.

from flask import Flask, render_template
from flask import url_for

app = Flask(__name__, static_url_path='/static')
@app.route('/')
def home():
    return render_template('home.html')
@app.route('/welcome')
def welcome():
    return render_template('welcome.html')
if __name__ == '__main__':
    app.run()

So, you are trying to send a file? Or show a file in an url? I assumed the later. Notice the use of url_for . This creates a link that will show your static file.

http://127.0.0.1:5000/send and http://127.0.0.1:5000/static/demo_data.json

from flask import Flask, render_template
from flask import url_for

app = Flask(__name__, static_url_path='/static')


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/send')
def send():
    return "<a href=%s>file</a>" % url_for('static', filename='demo_data.json')


if __name__ == '__main__':
    app.run()

But you also might want to check out https://github.com/cranmer/flask-d3-hello-world

You would need to define the view to send the data.

Something similar to :

from flask import Flask, render_template
from flask import url_for

app = Flask(__name__, static_url_path='/static/')
@app.route('/')
def home():
    return render_template('home.html')
@app.route('/welcome')
def welcome():
    return render_template('welcome.html')

@app.route('data/<filename>')
def get_json(filename):
    return send_from_dir

if __name__ == '__main__':
    app.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM