【发布时间】:2016-10-02 19:18:08
【问题描述】:
我正在尝试使用烧瓶实现一个简单的网络。当我尝试从 python 读取本地 json 数据并将其传递给前端时。失败了。
我的文件层次结构:
-app
-static
-data
predict.json
scripts.js
-templates
index.html
models.py
views.py
__init__.py
run.py
相关python部分:
import os
from app import app
@app.route("/test",methods=['GET'])
def get_local_json():
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "static/data",'predict.json')
data = json.load(open(json_url))
return data
scripts.js中的相关JS部分:
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT + "/test", function (data) { ...}
当我在我的电脑上运行这个网站时,控制台日志显示:
jquery-3.1.0.min.js:4 GET http://127.0.0.1:5000/predict.json 404(不是 找到)
似乎没有检测到我的修改(我的第一个版本只是从 JS 读取数据)。
非常感谢任何提示!
【问题讨论】:
-
您的网址是
http://127.0.0.1:5000/predict.json,您的路线是'predict',没有任何'.json'。 -
@vishes_shell 是的,这就是为什么我认为它没有检测到我的修改。 url 应该对应于@app.route(....),不是吗?
-
我相信它应该。但我也认为以这种方式提供静态文件是一种不好的做法。
-
@vishes_shell 抱歉,我不太明白。你的意思是从后端读取json并将其传递给前端?我只是用它来测试。稍后我将在后端调用机器学习模型并将预测结果传递给前端。
-
如果您要为视图的 url 创建一些模式,例如
'/predict_files/<file_name>',然后使用通过的file_name,就可以了。但是我认为保留这样一个依赖于文件名的 url 有点奇怪,因为如果你更改文件名,那么你需要更改app.route()。我希望你明白我想说什么。顺便说一句,将route中的'predict'更改为'predict.json'有帮助吗?
标签: jquery python json ajax flask