如何在Django中将python字典动态输出为html?

2024-05-16 20:54:26 发布

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

这是我从socket动态获取的数据,我想用django将它显示在一个类似于html中的键和值的表中。你知道吗

Received: 
{'power': 'ON', 'mode': 'AUTOMATIC', 'execution': 'ACTIVE', 'Xact': '235.70', 'Yact': '1468.86', 'Zact': '1.27', 'Xcom': '0.00', 'Ycom': '0.00', 'Zcom': '0.00', 'path_feedrate': '0.00', 'line': '1136849', 'Block': '1136849', 'program': '37262 S1 - .75 JET_imported_CNC.ORD\n'}
{'comms': 'NORMAL', '': '\n2018-08-08T17:11:51.0384', 'Sspeed': '60000.00\n'}
{'line': '1136860', 'Block': '1136860\n'}
{'Xact': '236.17', 'Xcom': '909.70', 'path_feedrate': '909.70\n'}
{'Xcom': '0.00', 'path_feedrate': '0.00', 'line': '1136872', 'Block': '1136872\n'}
{'line': '1136883', 'Block': '1136883\n'}
{'line': '1136895', 'Block': '1136895\n'}
{'line': '1136906', 'Block': '1136906\n'}
{'Xact': '236.52', 'Xcom': '677.44', 'path_feedrate': '677.44\n'}
{'Xcom': '0.00', 'path_feedrate': '0.00', 'line': '1136918', 'Block': '1136918\n'}
{'line': '1136929', 'Block': '1136929\n'}
{'line': '1136941', 'Block': '1136941\n'}

更多的输出。。。。。你知道吗

我试着用这个,但没用。你知道吗

{% block content %}
<table>
    {% for key, value in devDict.items() %}
    <tr>
        <td>{{ key }}</td>
        <td>{{ value }}</td>
    </tr>
    {% endfor %}
</table>
{% endblock content %}

{% block js %}
<script type="text/python3" src="{% static 'widgets/python/mtconnect.py'%}"></script>
{% endblock js %}

这是我的python脚本,这是我获取数据的方式:

import socket

HOST = "myHOST"
PORT = myPORT
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    buffer_size = 2048
    print("Received: ")
    while True:
        devData = s.recv(buffer_size).decode("utf-8").split("|")
        timeStamp = devData.pop(0)
        devDict = dict(zip(*([iter(devData)]*2)))
        print(devDict)
s.close()

Tags: pathkeylinetablesocketcontentblocktd
2条回答

看起来您收到了一个字典列表,首先需要遍历该列表。类似于:

<table>
    {% for line in devDict %}
    <tr>
        {% for key, value in line.items %}
                <td>{{ key }}</td>
                <td>{{ value }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

我面临的问题是,由于存在两种不同的协议,因此无法将数据从套接字呈现到浏览器。我得先在它们之间架起一座桥,从套接字到websocket。我是通过使用:https://github.com/yankov/webtcp来实现的。然后我就可以将数据从套接字渲染到浏览器。你知道吗

相关问题 更多 >