首页 > 解决方案 > 如何将脚本输出显示到网页烧瓶/django

问题描述

嗨,我创建了服务器客户端模型,其中客户端不断检查是否添加了新设备并将响应发送到服务器端它工作正常我想使用烧瓶或 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()

这是服务器端的输出

Device Added in wraith 192.168.10.9

Device Removed in wraith 192.168.10.9

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

标签: pythonflask

解决方案


Flask 和 Django 是为 HTTP 协议设计的 Web 应用程序框架,但您使用的是低级socket库,基本上没有使用任何已建立的协议。如果你想使用 Flask/Django,因为你想为你的设备观看客户端脚本的结果提供一个广播平台,那么我建议在你的客户端脚本中socket使用requests (link)来发送 HTTP POST 请求,而不是到您的 Flask/Django Web 应用程序。至于如何构建应用程序,有相应的教程。我确实想指出,极简主义的 Flask 可能比更自以为是的 Django 框架更适合这个项目。


推荐阅读