![](/img/trans.png)
[英]How to access a dictionary value in a for [django, python, html]
[英]How to dynamically output python dictionary to html in django?
这是我从套接字动态获取的数据,我想将其显示在带有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()
看起来您收到了一个字典列表,首先需要遍历该列表。 像这样:
<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做到了这一点。 然后我能够将数据从套接字渲染到浏览器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.