使用python urllib.request的zabbix API json请求

时间:2017-05-24 13:57:12

标签: python json urllib zabbix

我正在处理我的python项目,我从python2.6迁移到python 3.6。所以我不得不用urllib.request(以及.error和.parse)替换urllib2。

但我面临一个我无法解决的问题,这里是......

我想发送一个用JSON编写的请求,如下所示:

import json
import urllib2

data= json.dumps({
        "jsonrpc":"2.0",
        "method":"user.login",
        "params":{
             "user":"guest",
             "password":"password"
        }
        "id":1,
        "auth":None
     })

使用urllib2我没有遇到任何问题,我只需要创建请求:

req=urllib2.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})

发送时间:

response=urllib2.urlopen(req)

并且它很好但是现在使用urllib.request,我遇到了库提出的许多错误。检查我做了什么(请求在'数据'中是相同的):

import json
import urllib.request

data= json.dumps({
        "jsonrpc":"2.0",
        "method":"user.login",
        "params":{
             "user":"guest",
             "password":"password"
        }
        "id":1,
        "auth":None
     })
req = urllib.request.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})

response = urllib.request.urlopen(req) 

我收到此错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 524, in open
    req = meth(req)
  File "/tmp/Python-3.6.1/Lib/urllib/request.py", line 1248, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

所以我询问了这一点,并了解到我必须使用函数urllib.parse.urlencode()将我的请求转换为字节,所以我尝试在我的请求中使用它:

import urllib.parse

dataEnc=urllib.parse.urlencode(data)

发生了另一个错误:

Traceback (most recent call last):
  File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 842, in urlencode
    raise TypeError
TypeError

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 850, in urlencode
    "or mapping object").with_traceback(tb)
  File "/tmp/Python-3.6.1/Lib/urllib/parse.py", line 842, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object

我意识到json.dumps(数据)只是将我的数组/字典转换为字符串,这对于urllib.parse.urlencode函数无效,soooooo我从数据中退出了json.dumps并执行了此操作: / p>

import json
import urllib.request
import urllib.parse

data= {
        "jsonrpc":"2.0",
        "method":"user.login",
        "params":{
             "user":"guest",
             "password":"password"
         }
         "id":1,
         "auth":None
      }

dataEnc=urllib.parse.urlencode(data) #this one worked then

req=urllib.request.Request("http://myurl/zabbix/api_jsonrpc.php",data,{'Content-type':'application/json})

response = urllib.request.urlopen(req) #and this one too, but it was too beautiful

然后我看了一下回答并得到了这个:

b'{"jsonrpc":"2.0",
   "error":{
         "code":-32700,
         "message":"Parse error",
         "data":"Invalid JSON. An error occurred on the server while parsing the JSON text."}
    ,"id":1}

我想这是因为JSON消息不是json.dumped!

总有一个元素阻止我正确地执行请求,

所以我完全坚持下去,如果你们中的任何一个人有想法或另类,我会很高兴。

最好的问候

Gozu09

1 个答案:

答案 0 :(得分:2)

实际上你只需要将你的json数据作为字节序列传递:

data= {
    "jsonrpc":"2.0",
    "method":"user.login",
    "params":{
        "user":"guest",
        "password":"password"
    }
    "id":1,
    "auth":None
}

req = urllib.request.Request(
    "http://myurl/zabbix/api_jsonrpc.php",
    data=json.dumps(data).encode(),  # Encode a string to a bytes sequence
    headers={'Content-type':'application/json}
)
  

POST数据应该是字节,可迭代的字节或文件对象。它不能是str

类型

此错误意味着data参数应为字节的可迭代。

st = "This is a string"
by = b"This is an iterable of bytes"
by2 = st.encode() # Convert my string to a bytes sequence
st2 = by.decode() # Convert my byte sequence into an UTF-8 string

json.dumps()返回一个字符串,因此您必须调用json.dumps().encode()将其转换为字节数组。

顺便说一下,当你想转换一个将作为url参数传递的字符串时,会使用urlencode(:将空格字符转换为“%20”)。此方法的输出是字符串,而不是字节数组