urllib.request.urlopen返回内容长度为零的json数据

时间:2018-03-27 21:49:20

标签: python-3.x urlopen

我在覆盆子pi上设置了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
}

并调整音量。当php脚本在Raspberry上执行时,有一秒钟的延迟。

然而,当我尝试从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)

(我知道&#39;除了Exception&#39;不是pythonic,我还在为poc工作,并且一旦我开始工作就会进行适当的错误处理)

我怀疑某种类型的暂停,但不知道如何排除故障。任何想法或建议?

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

1 个答案:

答案 0 :(得分:0)

我必须设置请求标头

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

接受&#39;接受&#39;缺少的参数。默认情况下,仅设置了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);