向烧瓶提供静态 json 数据

Serving static json data to flask

我在 demo_data.json 中有 json 数据,我想将它们导入 Flask 应用程序中。我在放置在静态目录中的文件上收到 404,我的代码在下面,感谢您提前提出任何想法:

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')

您的 static_url_path 似乎有尾部斜线。删除多余的字符解决了这个问题。另请注意删除的最后一行。 return 调用不是必需的,return 之后的函数调用是语法错误。

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()

那么,您要发送文件吗?或者在 url 中显示文件? 我假设后者。注意 url_for 的使用。 这会创建一个 link 来显示您的静态文件。

http://127.0.0.1:5000/sendhttp://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()

但您可能还想看看 https://github.com/cranmer/flask-d3-hello-world

您需要定义发送数据的视图。

类似于:

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()