【问题标题】:Flask not picking up updated JSON [closed]Flask 没有获取更新的 JSON [关闭]
【发布时间】:2014-10-12 04:10:21
【问题描述】:

当 JSON 文件改变时,Flask 不会使用更新的 JSON 来渲染页面。我怎样才能解决这个问题? Python 版本 2.7.6 。烧瓶版本 0.9 。 我的存储库位于https://github.com/harishvc/githubanalytics

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

【问题讨论】:

  • 你必须出示代码。
  • 请展示您的工作、您尝试过的代码示例、flash 版本...任何有助于理解您的问题的信息都将帮助您获得适合您需求的答案
  • 我认为您想要双向绑定之类的东西。它可能不会自动以这种方式工作。您必须在代码中的某处加载更新的 JSON。
  • @vaultah 我更新了我的问题,提供更多信息和 GitHub 链接。

标签: python json flask


【解决方案1】:

您的问题不是 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 并使用您可能已添加到 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 加载一些东西,然后将数据保存到位于其他范围内的某个列表中,我会让它返回数据以使其更安全地使用。此建议以及其他错误/异常处理和其他清理工作留给您自己练习。

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多