0

我是获取/发布请求和 micropython 的绝对初学者。

我正在使用 micropython 将我的 ESP8266 Wemos D1 mini 编程为 HTTP 服务器。我的项目包括使用网站来控制连接到 D1 的新像素矩阵的 RGB 值(所有代码都在我的 GitHub 上:https ://github.com/julien123123/NeoLamp-Micro )。

基本上,该网站包含三个滑块:一个用于红色,一个用于绿色,一个用于蓝色。javascript 代码读取每个滑块的值并使用 POST 方法将其发送到 micropython 代码,如下所示:

getColors = function() {
  var rgb = new Array(slider1.value, slider2.value, slider3.value);
  return rgb;
};

postColors = function(rgb) {
  var xmlhttp = new XMLHttpRequest();
  var npxJSON = '{"R":' + rgb[0] + ', "G":' + rgb[1] + ', "B":' + rgb[2] + '}';
  xmlhttp.open('POST', 'http://' + window.location.hostname + '/npx', true);
  xmlhttp.setRequestHeader('Content-type', 'application/json');
  xmlhttp.send(npxJSON);
};

要在 micropython 中接收请求,这是我的代码:

conn, addr = s.accept()
request = conn.recv(1024)
request = str(request)
print(request)

响应打印如下:

b'POST /npx HTTP/1.1\r\nHost: 192.xxx.xxx.xxx\r\nConnection: keep-alive\r\nContent-Length: 27\r\nOrigin: http://192.168.0.110\r\nUser-Agent: Mozilla/5.0 (X11; CrOS x86_64 10323.46.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.107 Safari/537.36\r\nContent-type: application/json\r\nAccept: */*\r\nReferer: http://192.xxx.xxx.xxx/\r\nAccept-Encoding: gzip, deflate\r\nAccept-Language: fr,en;q=0.9,fr-CA;q=0.8\r\n\r\n{"R":114, "G":120, "B":236}'

对我来说唯一重要的是最后:{“R”:114,“G”:120,“B”:236}。我想使用这些值来更改我的 neopixel 对象的颜色值。

我的问题是如何处理响应,以便在响应末尾只保留包含 RGB 变量的字典?

提前谢谢(我快到了!)

4

1 回答 1

1

这与通用 python 数据类型更相关。的数据类型如前缀requestin所示。您将不得不使用将其转换为字符串bytesbb'POST /npx HTTP/1.1...\r\n{"R":114, "G":120, "B":236}'decode()

import json

request = b'POST /npx HTTP/1.1\r\nHost: 192.xxx.xxx.xxx\r\nConnection: keep-alive\r\nContent-Length: 27\r\nOrigin: http://192.168.0.110\r\nUser-Agent: Mozilla/5.0 (X11; CrOS x86_64 10323.46.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.107 Safari/537.36\r\nContent-type: application/json\r\nAccept: */*\r\nReferer: http://192.xxx.xxx.xxx/\r\nAccept-Encoding: gzip, deflate\r\nAccept-Language: fr,en;q=0.9,fr-CA;q=0.8\r\n\r\n{"R":114, "G":120, "B":236}'
data = request.decode()    # convert to str
rgb = data.split('\r\n')[-1:]   #split the str and discard the http header
for color in rgb:
    print(color, type(color))
    d = json.loads(color)
    print(d, type(d))

结果color是一个 json 对象的 str 表示,d它将为您提供一个 python dict 对象以用于进一步操作:

{"R":114, "G":120, "B":236} <class 'str'>
{'R': 114, 'G': 120, 'B': 236} <class 'dict'>
于 2018-03-08T07:56:41.397 回答