您好,我需要以表格形式在flask网页上显示我的输出。我现在以这种格式获得输出,其中wraith
是我的电脑名connected / disconnected
是status
和IP
。我将客户机输出保存在logs.log
文件中,然后读取该文件并将其显示在网页上,如下所示
wraith Connected USB from IP: 127.0.0.1
wraith Disconnected USB from IP: 127.0.0.1
wraith Connected USB from IP: 127.0.0.1
我需要像这样以表格格式显示这个输出
CLIENT
{
幽灵127.0.0.1已连接
幽灵127.0.0.1断开
比如这个例子
这是我的客户代码
import requests
import subprocess, string, time
import os
url = 'http://127.0.0.1:5000/'
name = os.uname()[1]
def on_device_add():
requests.post(f'{url}/device_add?name={name}')
def on_device_remove():
requests.post(f'{url}/device_remove?name={name}')
def detect_device(previous):
total = subprocess.run('lsblk | grep disk | wc -l', shell=True, stdout=subprocess.PIPE).stdout
time.sleep(3)
# if condition if new device add
if total > previous:
on_device_add()
# if no new device add or remove
elif total == previous:
detect_device(previous)
# if device remove
else:
on_device_remove()
# Infinite loop to keep client running.
while True:
detect_device(subprocess.run(' lsblk | grep disk | wc -l', shell=True , stdout=subprocess.PIPE).stdout)
这是我的烧瓶应用程序
from flask import Flask, request, Response
app = Flask(__name__)
@app.route("/device_add", methods=['POST'])
def device_add():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Connected USB from IP: {request.remote_addr}\n')
return 'ok'
@app.route("/device_remove", methods=['POST'])
def device_remove():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Disconnected USB from IP: {request.remote_addr}\n')
return 'ok'
@app.route("/", methods=['GET'])
def device_list():
with open('logs.log', 'r') as f:
return ''.join(f'<div>{line}</div>' for line in f.readlines())
实际上,您需要提供一些HTML来获取所需内容。通常,在“templates”目录中有一个单独的HTML模板,并且使用
render_template
。在本例中,我将模板构建为python脚本中的字符串,只是为了演示,但这在实际项目中是不可持续的循环数据行和插入单个点的语法基于Jinja2
相关问题 更多 >
编程相关推荐