[英]How to Get Data From a JSON File In Flask Server
我有一個 flask 服務器在我的 Pi 上運行。 我有一些數據存儲在另一個程序生成的 JSON 文件中。 如何加載這些數據並將其中的一部分發送到網頁? 我嘗試執行以下操作:
import json
@application.route('/WebPage/')
def webPage():
data = 0;
with open("jsonFile.json", 'r') as f:
data = json.load(f)
return render_template("freeGame.html", header=data['title'])
但這只會返回 500 內部服務器錯誤。 json 文件如下所示: {"title": "ExampleData"}
獲取數據的網頁如下所示:
{% extends "base.html" %}
{% block body %}
<h2>{ header }</h2>
{% endblock %}
當我使用 apache 運行它時,我也無法獲取從 flask 記錄的任何信息,所以我無法判斷 Z319C3206A7F10C17C3B9116D4A9576 是否檢測到任何錯誤。 我嘗試只使用f=open("file.json", 'r')
和f.close()
獲取文件,但這也沒有用。
不完全是您的代碼,但我嘗試構建一個簡單的測試示例。 我有3個文件。
./app.py
import json
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index_page():
fileData = 0;
with open('data.json', 'r') as f:
fileData = json.load(f)
f.close()
return render_template('index.html', fileData = fileData)
./templates/index.html
<!doctype html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1> The message is: </h1>
<h3>
{{fileData["msg"]}}
</h3>
</body>
</html>
./data.json
{
"msg" : "This message is in a JSON File"
}
我得到這個 output:
<!doctype html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1> The message is: </h1>
<h3>
This message is in a JSON File
</h3>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.