将使用POST请求接收的数据打印到使用Flask的本地服务器

问题描述 投票:1回答:2

因此,显然我正在尝试将我的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>

上面是我在template目录下的text.html页面。任何帮助将不胜感激:D

python python-3.x flask python-requests flask-restful
2个回答
0
投票

请在下面尝试:

from flask import jsonify, Flask, make_response,request, render_template
from flask_restful import Resource, Api

# creating the flask app 
app = Flask(__name__) 
# creating an API object 
api = Api(app) 

@app.route("/getData", methods=['POST', 'GET'])
def getInfo():
        textInput = request.form["data"]
        print(textInput)
        return render_template("text.html",text=textInput)
if __name__ == '__main__':
    app.run(debug=True)

并且在您的HTML中使用Jinja,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>
{{ text }}
</body>
</html>

0
投票

您不需要显式编写return make_response...,只需要使用render_template就足够了。

from flask import Flask, request, render_template
from flask_restful import Resource, Api

# creating the flask app 
app = Flask(__name__) 
# creating an API object 
api = Api(app) 

@app.route("/getData", methods=['POST', 'GET'])
def getInfo():
    textInput = request.form["data"]
    print(textInput)
    return render_template("text.html", text=textInput)


if __name__ == '__main__':
    app.run(debug=True)

此外,请确保您的项目结构正确,请参阅official documentation,因为如果您有某些特定的Flask项目结构。

有关如何呈现模板的更多信息,请参见官方文档quickstart,它说明了如何正确使用它,

© www.soinside.com 2019 - 2024. All rights reserved.