如何将字符串转换为字典或某种形式(来自 websocket 客户端)
How to convert string to dictionary or some sort (from websocket client)
如果 websocket 客户端连接到 websocket 服务器,它将发送所有这些标签:
GET /x.css HTTP/1.1
Host: 192.168.2.12
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: http://192.168.2.12/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
这是一根大绳子。有没有办法从中提取单个组件?例如
print(data['GET'])
print(data['Host'])
它打印请求的数据?
您可以逐行阅读它,并用“:”或“”分隔符分隔每一行,然后将其制成字典。
text = '''GET /x.css HTTP/1.1
Host: 192.168.2.12
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: http://192.168.2.12/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4'''
dic = {}
for line in text.splitlines():
if ': ' in line:
key, val = line.split(': ')
dic[key] = val
else:
arr = line.split(' ')
dic[arr[0]] = ' '.join(arr[1:])
或更简洁一点,您按 space 拆分并从键名中删除“:”:
dic = {}
for line in text.splitlines():
arr = line.split(' ')
dic[arr[0].rstrip(':')] = ' '.join(arr[1:])
如果 websocket 客户端连接到 websocket 服务器,它将发送所有这些标签:
GET /x.css HTTP/1.1
Host: 192.168.2.12
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: http://192.168.2.12/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
这是一根大绳子。有没有办法从中提取单个组件?例如
print(data['GET'])
print(data['Host'])
它打印请求的数据?
您可以逐行阅读它,并用“:”或“”分隔符分隔每一行,然后将其制成字典。
text = '''GET /x.css HTTP/1.1
Host: 192.168.2.12
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: http://192.168.2.12/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4'''
dic = {}
for line in text.splitlines():
if ': ' in line:
key, val = line.split(': ')
dic[key] = val
else:
arr = line.split(' ')
dic[arr[0]] = ' '.join(arr[1:])
或更简洁一点,您按 space 拆分并从键名中删除“:”:
dic = {}
for line in text.splitlines():
arr = line.split(' ')
dic[arr[0].rstrip(':')] = ' '.join(arr[1:])