简体   繁体   English

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

[英]Printing Data Received using POST Request to local server using Flask

So, apparently I am trying to send data from my openCV webcam to a local sever spun using Flask.所以,显然我正在尝试将数据从我的 openCV 网络摄像头发送到使用 Flask 旋转的本地服务器。 I am able to receive the data and print it on terminal, however, I am not really sure as to how to print it on a webpage.我能够接收数据并在终端上打印它,但是,我不确定如何在网页上打印它。

This is my program :这是我的程序:

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)

I am sending data from webcam.py using requests module via post request.我通过发布请求使用请求模块从 webcam.py 发送数据。 The data is received and currently printed on terminal.数据被接收并当前打印在终端上。 However, I want it to be redirected to text.html.但是,我希望它被重定向到 text.html。

data = {"data": res} 
requests.post(url = API_ENDPOINT, data = data)

The above is the code snippet I use to send data from webcam.py to API_ENDPOINT (127.0.0.1:5000/getData).以上是我用来将数据从 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>

The above is my text.html page under templates directory.以上是我在templates目录下的text.html页面。 Any Help will be appreciated :D任何帮助将不胜感激:D

The problem with your code is that you send data from OpenCV webcam to a local server and from local server you return a response to openCV webcam and that's why you see data in the terminal as you print it and you can't see data in the webpage of flask app as you don't have that data, because you have lost data at the moment you have returned a response to the openCV webcam .您的代码的问题在于,您将数据从OpenCV webcam送到local server然后从local serveropenCV webcam返回响应,这就是为什么您在打印时在终端中看到数据而在终端中看不到数据的原因Flask 应用程序的网页,因为您没有该数据,因为您在向openCV webcam返回响应时丢失了数据。

In this case, you could use 1 of the 3 approaches.在这种情况下,您可以使用 3 种方法中的一种。

  1. Using a database, like sqlite3 and save received data from the openCV webcam , but then you will need to do more, like create models and etc.使用数据库,如sqlite3并保存从openCV webcam接收到的数据,但是你需要做更多的事情,比如创建模型等。

  2. Save data received from OpenCV webcam to a file - quicker option to verify that everything works (the one I will use in my code example)将从OpenCV webcam接收到的数据保存到文件 - 验证一切正常的更快选项(我将在我的代码示例中使用的选项)

  3. Using flask.session and saving data to flask session and then reading from it as you would read data from python dictionary.使用flask.session并将数据保存到flask session,然后像从python 字典中读取数据一样从中读取数据。

In these cases, when you open your flask web app in the browser, you need to read data from either DB , file or flask.session .在这些情况下,当您在浏览器中打开您的flask.session Web 应用程序时,您需要从DBfileflask.session读取数据。

In this example, I will use a file named data.txt to which I will write (I will use a that means open file to append to the end of a file, then the old data will be left when you will send multiple requests from OpenCV webcam ) information received from OpenCV webcam server.在这个例子中,我将使用一个名为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)

This way your OpenCV webcam will receive 200 response with a message.这样您的OpenCV webcam将收到200消息响应。 Then you can navigate to your web app /getData page, then the request method will be GET and then it will read the content of a file data.txt and will pass this to the webpage you have just opened.然后您可以导航到您的网络应用程序/getData页面,然后请求方法将为GET ,然后它将读取文件data.txt的内容并将其传递给您刚刚打开的网页。

Make sure that you can access data.txt , it should be placed in the same directory as your app exists (at least with this example, but you should make more appropriate structure later on or at all use the sqlite3 database for local development).确保您可以访问data.txt ,它应该放置在与您的应用程序存在相同的目录中(至少在这个示例中,但您应该稍后制作更合适的结构,或者完全使用sqlite3数据库进行本地开发)。

Try this below:试试这个:

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)

And in your HTML use Jinja like following below:在你的 HTML 中使用 Jinja,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM