【发布时间】:2018-04-25 19:55:23
【问题描述】:
我正在编写一个脚本来检查是否存在 json 文件。如果是,那么它使用flask render_template 函数来使用数据来加载网页。如果没有,脚本会查询数据库,将数据放入 json 格式,然后创建并写入 json 文件。这是一些示例代码。
from flask import render_template
import json
import os
title = "Tests"
jsonFile = "tests.json"
if os.path.exists(jsonFile):
return render_template('tests.html', title=title, data='tests')
else:
data = '{"tests":[{"id":"1","ip_addy":"IP1","name":"name1"},
{"id":"2","ip_addy":"IP2","name":"name2"},
{"id":"3","ip_addy":"IP3","name":"name3"}
]}'
with open(jsonFile, "w+") as f:
json.dump(data, f)
f.close()
return render_template('tests.html', title=title, data=data)
它写入 test.json 文件就好了,但是当我在创建 test.json 后重新加载 tests.html 页面时, html 说没有要显示的记录。是不是我创建的json文件不正确?
【问题讨论】:
-
关闭(f) 好吗?对我来说,python 抱怨,但可能是在 python 3.6 中,close(f) 变成了 f.close()。同样在您的情况下,如果 jsonFile 存在于脚本开头但为空,它将使用数据呈现为“测试”。
-
谢谢你,西蒙。实际上,我确实有 f.close() 而不是 close(f)。 json文件不为空。
-
如果它存在,您将在 if 语句中呈现模板。和 data ='test' 在您的模板中。如果您想使用文件中的数据读取渲染,您应该尝试在渲染之前读取文件的内容,然后使用第一条语句传递它。