Flask未能获取更新的JSON

-4 投票
1 回答
1031 浏览
提问于 2025-04-18 17:45

当JSON文件发生变化时,Flask没有使用更新后的JSON来渲染页面。我该如何解决这个问题?我的Python版本是2.7.6,Flask版本是0.9。我的代码库可以在这里找到:https://github.com/harishvc/githubanalytics

#Starting Flask
#!flask/bin/python
from app import app
app.run(debug = True)

1 个回答

3

你的问题不是JSON文件在更改时没有更新,而是你的代码只在导入这个模块的时候加载了一次这个文件,之后就再也没有加载过了。这样一来,显而易见的问题就出现了。

为了更好地帮助你,你应该把相关的代码部分放到问题里,而不仅仅是链接。这里我帮你做了:

with open('path/to/jsonfile.json') as f:
    data = json.load(f)

mydata = []
for row in data['rows']:
    mydata.append({'name': result_row[0], 'count' : result_row[1],})

@app.route('/')
@app.route('/index')
def index():
    return render_template("index.html", data=mydata)

这基本上就是你的代码。在你的index路由处理程序中,没有任何地方会重新加载这个JSON文件,也不会把你可能添加的新数据填充到mydata列表中。所以,你需要创建一个方法来做到这一点。

mydata = []

def refresh_data():
    mydata.clear()  # clear the list on the module scope

    with open('path/to/jsonfile.json') as f:
        data = json.load(f)

    for row in data['rows']:
        mydata.append({'name': result_row[0], 'count' : result_row[1],})

然后简单地让路由处理程序调用这个refresh_data函数:

@app.route('/')
@app.route('/index')
def index():
    refresh_data()
    return render_template("index.html", data=mydata)

我个人会更进一步,让refresh_data加载一些东西,然后把数据保存到其他地方的一个列表中,我会让它返回数据,这样使用起来会更安全。这个建议,以及其他的错误处理和清理工作,就留给你自己去完成吧。

撰写回答