【问题标题】:urllib.request.urlopen of json data returning content-length zerojson 数据的 urllib.request.urlopen 返回内容长度为零
【发布时间】:2018-09-06 10:59:20
【问题描述】:

我在树莓派上设置了一个 RESTful api,它连接到我的立体声音响以调节音量。如果我从 YARC(Chrome 的 REST 客户端测试扩展)进行测试,它就可以工作:

http://1.2.3.4/yamaha/volume/relative/up/1/

返回这个

{
  "status": "OK",
  "direction1": "up",
  "halfdecibels": "1",
  "volume": "-28.0"
}

响应头是

{
  "date": "Tue, 27 Mar 2018 21:20:53 GMT",
  "server": "Apache/2.4.25 (Raspbian)",
  "connection": "Keep-Alive",
  "keep-alive": "timeout=5, max=100",
  "content-length": "69",
  "content-type": "application/json, text/plain, */*",
  "status": 200
}

并确实调整了音量。在 Raspberry 上执行 php 脚本时会有大约一秒的延迟。

但是,当我尝试从 AWS Lambda 运行时,它不起作用。它确实调整了音量,所以请求在那里;但返回的响应是空的。

Lambda 上的 Python 函数

url = "http://1.2.3.4/yamaha/" \
      "volume/relative/{}/{}/".format(direction, half_decibels)

request = urllib.request.Request(url)
try:
    response=urllib.request.urlopen(request)
    r = response.read()
    print("response from url <{}>".format(r))
    print("headers {}".format(response.headers))
    data = json.loads(r)
except Exception as e:
    print("error occurred connecting to stereo {}".format(str(e)))
    return build_volume_response(OK, "25")

输出是

response from url <b''>
headers Date: Tue, 27 Mar 2018 21:45:35 GMT
Server: Apache/2.4.25 (Raspbian)
Content-Length: 0
Connection: close

error occurred connecting to stereo Expecting value: line 1 column 1 (char 0)

(我知道 'except Exception' 不是 Pythonic,我仍在研究 poc,一旦我开始工作,我会进行适当的错误处理)

我怀疑某种超时,但不知道如何排除故障。有什么想法或建议吗?

更新:我从 php 脚本欺骗了对立体声的调用,因此没有延迟;但我仍然得到相同的零长度响应。所以我不再将超时视为根本原因

【问题讨论】:

    标签: python-3.x urlopen


    【解决方案1】:

    我必须设置请求标头

    hdr = { 'User-Agent' : 'Python-urllib/3.6', 
            'Connection' : 'keep-alive',
            'Accept' : 'application/json, text/plain, */*',
          }
    req = urllib.request.Request(url, headers=hdr)
    

    缺少的是“Accept”参数。默认情况下只设置了 User-Agent。

    为了解决请求标头问题,我将其添加到树莓上的 php 脚本中

            $txt = "request headers\n";
            foreach (getallheaders() as $name => $value)
            {
                    $txt .= "'" . $name . "' : '" . $value . "'\n";
            }
            $myfile = file_put_contents('/var/www/logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
            fwrite($myfile, "\n". $txt);
            fclose($myfile);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      相关资源
      最近更新 更多