烧瓶和插座io

时间:2017-08-24 08:40:46

标签: python sockets flask

我正在试验烧瓶并有一个基本的网页设置,它给我一个数据字段来填写。一切正常,但我遇到了通过套接字连接发送数据到服务器的问题。代码如下:

from flask import Flask, render_template, request
import socket
import sys

app = Flask(__name__)

app.static_folder = 'static'

HOST, PORT = '', 8888


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/success', methods=['POST'])
def success():
    if request.method == 'POST':
        if request.form['Update'] == 'Update':
            messsage_name = request.form["message_name"]

            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as soc:
                # connect to server if we have a post
                soc.connect((HOST, PORT))
                soc.sendall(bytes(messsage_name + "\n", "utf-8"))
    return render_template("index.html")


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

我想打开套接字一次,然后每次按下更新按钮时通过它发送数据,目前我可以让它工作的唯一方法是继续按照上面的代码打开套接字。在烧瓶应用程序退出之前,我不希望套接字关闭。

是实现目标的最佳方式

感谢

1 个答案:

答案 0 :(得分:1)

我认为你的头衔错了。在您的示例中,没有使用socketIO库。 要在您的烧瓶应用程序中使用socketIO,您需要安装这样的库:

pip install flask-socketio

然后你可以在你的python文件中导入它:

from flask_socketio import SocketIO, emit

然后,您可以使用socketIO并向网页发送一些消息/数据。

顺便说一句,只要你的Flask服务器开启,你的套接字就像以前一样初始化。更多信息over there.

如果你的目标是使用Python套接字,那么你必须编辑你的问题标题。