Python 如何将脚本输出显示到网页flask/django

Python 如何将脚本输出显示到网页flask/django,python,flask,Python,Flask,嗨,我创建了服务器-客户机模型,在该模型中,客户机不断检查是否添加了新设备,并将响应发送到服务器端。工作正常。我希望使用flask或Django在web浏览器上连续显示从客户机到服务器的响应 这是我的客户代码 from socket import * import subprocess, string, time host = 'localhost' # '127.0.0.1' can also be used port = 53000 sock = socket() # Connecti

嗨,我创建了服务器-客户机模型,在该模型中,客户机不断检查是否添加了新设备,并将响应发送到服务器端。工作正常。我希望使用flask或Django在web浏览器上连续显示从客户机到服务器的响应

这是我的客户代码

from socket import *
import subprocess, string, time

host = 'localhost'  # '127.0.0.1' can also be used
port = 53000
sock = socket()

# Connecting to socket
sock.connect((host, port))  # Connect takes tuple of host and port

def detect_device(previous):
    import socket
    username2 = socket.gethostname()
    ip=socket.gethostbyname(username2)
    total = subprocess.run('lsblk | grep disk | wc -l', shell=True, stdout=subprocess.PIPE).stdout
    time.sleep(3)

# if conditon if new device add
    if total>previous:
     response = "Device Added in " + username2 + " " + ip
     sock.send(response.encode())
# if no new device add or remove
    elif total==previous:
     detect_device(previous)
# if device remove
    else:
     response = "Device Removed in " + username2 + " " + ip

     sock.send(response.encode())
# Infinite loop to keep client running.


while True:
    data = sock.recv(1024)
    if (data == b'Hi'):
        while True:
            detect_device(subprocess.run(' lsblk | grep disk | wc -l', shell=True , stdout=subprocess.PIPE).stdout)

sock.close() 
这是我的服务器端代码

from socket import *
# Importing all from thread
import threading

# Defining server address and port
host = 'localhost'
port = 53000

# Creating socket object
sock = socket()
# Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
# Listening at the address
sock.listen(5)  # 5 denotes the number of clients can queue

def clientthread(conn):
    # infinite loop so that function do not terminate and thread do not end.
    while True:
        # Sending message to connected client
        conn.send('Hi'.encode())  # send only takes string
        data =conn.recv(1024)
        print (data.decode())
while True:
    # Accepting incoming connections
    conn, addr = sock.accept()
    # Creating new thread. Calling clientthread function for this function and passing conn as argument.
    thread = threading.Thread(target=clientthread, args=(conn,))
    thread.start()

conn.close()
sock.close()
这是服务器端的输出

幽灵192.168.10.9中添加的设备

在幽灵192.168.10.9中删除的设备


我需要在网页上显示此输出。

Flask和Django是为HTTP协议设计的web应用程序框架,但您使用的是低级的
套接字
库,基本上不使用任何已建立的协议。如果您想使用Flask/Django,因为您想为设备观看客户端脚本的结果提供一个广播平台,那么我建议您不要使用
socket
,而是在客户端脚本中使用
requests
,向Flask/Django Web应用发送HTTP POST请求。至于如何构建这个应用程序,这里有相关的教程。我想指出的是,与更固执己见的Django框架相比,极简的Flask可能更适合这个项目。

hi,您能更改我发布请求的客户端代码吗?谢谢。@niftykhan展示了如何使用该库执行HTTP请求,包括post方法。至于您需要的确切代码,这将取决于您的web应用程序预期的请求结构(也称为您将在客户端和服务器之间构建的API,尽管它不需要复杂)。