我的python脚本如下所示。该脚本读取line
数据并将其作为发布请求发送。有时,当eventStream发送包含数据的新消息时。它始终没有line
的数据,因此在发送第二个示例之前,它可以正常工作。{哪个可以是随机的,}
这是流中两个事件的示例。第一个包含来自“行”的数据。第二个例子没有。
示例1:包含“行”中的数据
data: {"ident":"8micxp7q5w5tfsrkkw9iys7l2ead7tls","line":[[300,161],[301,161],[301,161],[302,161],[302,161],[307,166],[307,166],[315,176],[315,176],[319,181],[319,181],[321,185],[321,185],[322,186],[322,186]],"lineColor":"db1f1f","lineWidth":"1","opacity":"75","status":"d","channel":"_index"}
示例2:不包含“行”数据。
data: {"ident":"c4duzpz3aw3uurbmzmzxe4u43y7xiaup","status":"w","channel":"_index"}
因此,当第二个eventStream消息发送时(示例2),我的脚本崩溃了。我希望它能够持续运行,如果找不到"line"
数据,只需等待它就可以找到。找到后,发送请求。
下面的我的python脚本:
import json
import requests
from sseclient import SSEClient as EventSource
url = "URL"
querystring = {"ing":"_index"}
headers = {
'content-type': "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW",
'Content-Type': "application/x-www-form-urlencoded",
'X-Requested-With': "XMLHttpRequest",
'Accept': "*/*",
'User-Agent': "PostmanRuntime/7.13.0",
'Cache-Control': "no-cache",
'Postman-Token': "a4cccbb2-ec51-4694-b198-e733f1f10e4c,ed3c968e-b8b2-4168-abef-51025096933d",
'Host': "URLHERE",
'cookie': "i=cloyfj1bio8uvxlqrkfkczqxo1pmx7m5; o=100; w=15; c=t44q; h=_-g00000____5aU00bH_GqCFXg3g_SY0gtx1J808RNApYLbO6g41X1wo____T000R01Puw3rMVU0t44q7w3F0afp4NcjXz00; a=lnpe0l; oi=qld8gxkfrzalpvqgydze7dzbm8p1r2zp",
'accept-encoding': "gzip, deflate",
'content-length': "713",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
url1 = 'http://URLHERE.com/'
for event in EventSource(url1):
if event.event == 'message':
try:
change = json.loads(event.data)
except ValueError:
continue
else:
print('{ident} drew {status}'.format(**change))
payload = {'l': '{line}'.format(**change), 'c': '00ff00', 'w': '{lineWidth}'.format(**change), 'o': '100', 'f': '1', '_': 'false'}
requests.request("POST", url, data=payload, headers=headers, params=querystring)
答案 0 :(得分:0)
只需测试"line"
中是否存在change
键:
for event in EventSource(url1):
if event.event == 'message':
try:
change = json.loads(event.data)
except ValueError:
continue
# no 'else' needed here, `continue` will skip to the next iteration
print('{ident} drew {status}'.format(**change))
# `change` is a standard Python dict so you can
# easily test if a given key is set
if "line" in change:
payload = {'l': '{line}'.format(**change), 'c': '00ff00', 'w': '{lineWidth}'.format(**change), 'o': '100', 'f': '1', '_': 'false'}
requests.request("POST", url, data=payload, headers=headers, params=querystring)