如何从Python发布数据并进入Flask前端
我目前的问题是连接前端和后端。我已经在init.py中完成了所有的数据处理,它在文件末尾有一条包含数据的有效json消息。现在,我想将这些数据发布到flask前端,并获取前端中的数据,以便使用这些数据在index.html上可视化某些内容。我不知道如何从这里发帖,因为我尝试过从init.py发帖,但它不起作用 文件结构:如何从Python发布数据并进入Flask前端,python,flask,Python,Flask,我目前的问题是连接前端和后端。我已经在init.py中完成了所有的数据处理,它在文件末尾有一条包含数据的有效json消息。现在,我想将这些数据发布到flask前端,并获取前端中的数据,以便使用这些数据在index.html上可视化某些内容。我不知道如何从这里发帖,因为我尝试过从init.py发帖,但它不起作用 文件结构: -Application -app -templates -index.html -__init__.py -routes.py -
-Application
-app
-templates
-index.html
-__init__.py
-routes.py
-check.py
init.py:
from flask import Flask
import requests
import json
app = Flask(__name__)
from app import routes
#MESSAGE IS A JSON AND HAS DATA
message=json.dumps(dicts)
routes.py:
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
@app.route('/getjson', methods = ['GET'])
def index():
user = {'username': 'Me'}
return render_template('index.html', title='Home', user=user)
index.html:
<html>
<head>
<title>{{ title }} - Status Checker</title>
</head>
<body>
<h1>Hello, Me!</h1>
</body>
</html>
添加此r=requests.post(“http://localhost:5000/getjson“,json=message)
to init.py给我一个错误:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /getjson (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x04ED1250>: Failed to
establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
requests.exceptions.ConnectionError:HTTPConnectionPool(host='localhost',port=5000):url:/getjson超过了最大重试次数(由NewConnectionError(':失败
建立新连接:[WinError 10061]无法建立连接,因为目标计算机主动拒绝了它])
您最好在路由内加载消息,如下所示:
def index():
user = {'username': 'Me'}
message=json.dumps(dicts)
return render_template('index.html', title='Home', user=user, message=message)
然后,您必须在html中添加一个jinja循环,以显示部分消息结构。如果您需要帮助,请告诉我,添加一些有关消息的信息以及您希望在html中显示的内容。好的,因此我将处理从init.py移到routes.py,并将消息放入index()。现在如何在html文件中呈现json?请看这里:
def index():
user = {'username': 'Me'}
message=json.dumps(dicts)
return render_template('index.html', title='Home', user=user, message=message)