python - 使用 Flask 将使用 POST 请求接收到的数据打印到本地服务器
问题描述
因此,显然我正在尝试将数据从我的 openCV 网络摄像头发送到使用 Flask 旋转的本地服务器。我能够接收数据并在终端上打印,但是,我不确定如何在网页上打印。
这是我的程序:
from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api
# creating the flask app
from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
@app.route("/getData", methods=['POST', 'GET'])
def get():
if request.method == 'POST':
textInput = request.form["data"]
print(textInput)
return render_template("text.html",text=textInput)
else:
return render_template("text.html")
@app.route("/", methods=['GET'])
def contact():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
我通过发布请求使用请求模块从 webcam.py 发送数据。数据已接收并当前打印在终端上。但是,我希望它被重定向到 text.html。
data = {"data": res}
requests.post(url = API_ENDPOINT, data = data)
以上是我用来将数据从 webcam.py 发送到 API_ENDPOINT (127.0.0.1:5000/getData) 的代码片段。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Sign to Speech</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,
body {
background-color: #FFC107
}
</style>
</head>
<body>
<h4>{{text}}</h4>
</body>
</html>
以上是我的templates目录下的text.html页面。任何帮助将不胜感激:D
解决方案
您的代码的问题是您将数据从a 发送OpenCV webcam
到 alocal server
并从local server
您返回响应openCV webcam
,这就是为什么您在打印时在终端中看到数据而在烧瓶应用程序的网页中看不到数据的原因没有该数据,因为在您返回对openCV webcam
.
在这种情况下,您可以使用 3 种方法中的一种。
使用数据库,喜欢
sqlite3
并保存从 接收到的数据openCV webcam
,但是你需要做更多的事情,比如创建模型等。将接收
OpenCV webcam
到的数据保存到文件中 - 验证一切正常的更快选项(我将在我的代码示例中使用的那个)使用
flask.session
数据并将数据保存到烧瓶会话,然后像从 python 字典中读取数据一样从中读取数据。
DB
在这些情况下,当您在浏览器中打开烧瓶网络应用程序时,您需要从file
或读取数据flask.session
。
在这个例子中,我将使用一个名为data.txt
我将写入的文件(我将使用a
它意味着打开文件以追加到文件的末尾,然后当您发送多个请求时,旧数据将被留下OpenCV webcam
)从接收到的信息OpenCV webcam
服务器。
from flask import Flask, request, render_template, jsonify
# creating the flask app
app = Flask(__name__)
@app.route("/getData", methods=['POST', 'GET'])
def getInfo():
if request.method == 'POST':
text_input = request.form["data"]
with open('data.txt', 'a') as data_file:
data_file.write(text_input)
return jsonify({'message': 'Data saved sucessfully!'}), 200
else:
text_input = None
with open('data.txt', 'r') as data_file:
text_input = data_file.read()
return render_template("text.html", text=text_input)
if __name__ == '__main__':
app.run(debug=True)
这样,您OpenCV webcam
将收到200
带有消息的响应。然后你可以导航到你的网页应用程序/getData
页面,然后请求方法将是GET
,然后它将读取文件的内容data.txt
并将其传递给你刚刚打开的网页。
确保您可以访问
data.txt
,它应该与您的应用程序存在于同一目录中(至少在此示例中,但您应该稍后制作更合适的结构或完全使用sqlite3
数据库进行本地开发)。