Python Flask 加载本地 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21133976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:08:57  来源:igfitidea点击:

Flask load local json

pythonjsonflask

提问by kOssi

I am struggling with how to load a local json in flask.

我正在努力研究如何在烧瓶中加载本地 json。

from flask import Flask, render_template, json, url_for

def taiwan():
    json_data = open(url_for('static', filename="data/taiwan.json"))
    data = json.load(json_data)
    return render_template('taiwan.jade', data=data)

This raises an IOError: No such file or directory: '/static/css/taiwan.json'. But it still exists.

这会引发 IOError: No such file or directory: '/static/css/taiwan.json'。但它仍然存在。

Any suggestions

有什么建议

采纳答案by kOssi

I ended up with this:

我结束了这个:

import os
from flask import Flask, render_template, url_for, json

def showjson():
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    json_url = os.path.join(SITE_ROOT, "static/data", "taiwan.json")
    data = json.load(open(json_url))
    return render_template('showjson.jade', data=data)

回答by Krzysztof Rosiński

You should use the path of Your static dir, to obtain the file, url_for gets the URI abs path, not fs path. Try this

您应该使用您的静态目录的路径来获取文件, url_for 获取 URI abs 路径,而不是 fs 路径。尝试这个

json_data = open(os.path.join(your_static_dir, "data", "taiwan.json"), "r")

回答by cowgill

Dynamically get your static directory and includes a datasub-dir which contains the .jsonfile to load.

动态获取您的静态目录并包含一个data包含.json要加载的文件的子目录。

import os
from flask import Flask, render_template, json, current_app as app

# static/data/test_data.json
filename = os.path.join(app.static_folder, 'data', 'test_data.json')

with open(filename) as test_file:
    data = json.load(test_file)

return render_template('index.html', data=data)