如何使用flask在表中显示文件的输出

2024-03-28 17:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我需要以表格形式在flask网页上显示我的输出。我现在以这种格式获得输出,其中wraith是我的电脑名connected / disconnectedstatusIP。我将客户机输出保存在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断开

比如这个例子

enter image description here

这是我的客户代码

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())

Tags: namefromimportiplogaddifrequest
1条回答
网友
1楼 · 发布于 2024-03-28 17:07:40

实际上,您需要提供一些HTML来获取所需内容。通常,在“templates”目录中有一个单独的HTML模板,并且使用render_template。在本例中,我将模板构建为python脚本中的字符串,只是为了演示,但这在实际项目中是不可持续的

循环数据行和插入单个点的语法基于Jinja2

from flask import Flask, request, render_template_string

app = Flask(__name__)


TABLE_TEMPLATE = """
<style>
   table, th, td {
   border: 1px solid black;
   }
</style>
<table style="width: 100%">
   <thead>
      <th>Client</th>
      <th>IP</th>
      <th>Status</th>
   </thead>
   <tbody>
      {% for row in data %}
      <tr>
         <td>{{ row.client }}</td>
         <td>{{ row.ip }}</td>
         <td>{{ row.status }}</td>
      </tr>
      {% endfor %}
   </tbody>
</table>
"""

@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():
    keys = ['client', 'ip', 'status']
    data = []
    with open('logs.log', 'r') as f:
        for line in f:
            row = line.split()
            data.append(dict(zip(keys, [row[0], row[-1], row[1]])))
            
    return render_template_string(TABLE_TEMPLATE,
                                  data=data)

相关问题 更多 >