TypeError:不能将字节连接到str python3

时间:2017-05-10 19:21:05

标签: python python-3.x urllib3

我尝试使用python3urllib3中发送HTTP请求。

以下是代码段

request_body = {'grant_type':'password','username': username,'password': password}
request_headers = {'Content-Type' : 'application/x-www-form-urlencoded','Authorization': "hash string"}
http = urllib3.PoolManager()
response = http.request('POST', 'https://api/url/endpoint', headers=request_headers, body=request_body)

但是当我尝试执行它时,它会抛出以下错误。

  

TypeError:无法将字节连接到str

完整追溯

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Mubin/anaconda/lib/python3.6/site-
packages/urllib3/request.py", line 70, in request
**urlopen_kw)
File "/Users/Mubin/anaconda/lib/python3.6/site-
packages/urllib3/request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
File "/Users/Mubin/anaconda/lib/python3.6/site-
  packages/urllib3/poolmanager.py", line 321, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "/Users/Mubin/anaconda/lib/python3.6/site-
  packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/Users/Mubin/anaconda/lib/python3.6/site-
  packages/urllib3/connectionpool.py", line 356, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/Users/Mubin/anaconda/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Users/Mubin/anaconda/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Users/Mubin/anaconda/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Users/Mubin/anaconda/lib/python3.6/http/client.py", line 1064, in _send_output
+ b'\r\n'

有人可以指出我做错了吗?

修改

request_body类型检查

>>> type(request_body)
    <class 'dict'>
>>> type(request_body['username'])
    <class 'str'>
>>> type(request_body['password'])
    <class 'str'>
>>> type(request_body['grant_type'])
    <class 'str'>

2 个答案:

答案 0 :(得分:2)

我认为您打算使用fields参数代替body

http.request('POST', 'https://api/url/endpoint', headers=request_headers, fields=request_body)

就像这个example

一样

答案 1 :(得分:0)

我找到了解决此问题的方法。 我试图从钥匙斗篷获得令牌。 钥匙斗篷除外:
POST请求
内容类型:application/x-www-form-urlencoded
在正文中带有凭据

我在https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.request中读过:

  

request_encode_body(方法,URL,字段=无,标头=无,encode_multipart = True,multipart_boundary =无,** urlopen_kw)

     

使用urlopen()和在正文中编码的字段进行请求。这对于POST,PUT,PATCH等请求方法很有用。

     

当encode_multipart = True(默认值)时,则使用urllib3.filepost.encode_multipart_formdata()对具有适当内容类型的有效负载进行编码。否则,urllib.urlencode()与“ application / x-www-form-urlencoded”内容类型一起使用。

所以我成功完成了这样的请求:

    data = {
        'client_id': 'front',
        'grant_type': 'password',
        'username': settings.AUTH_REST_ADMIN_API_USER,
        'password': settings.AUTH_REST_ADMIN_API_PASSWORD
    }

    r = http.request_encode_body(
        'POST',
        settings.token_endpoint,
        encode_multipart=False,
        headers={
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': settings.AUTH_AUTHORIZATION
        },
        fields=data
    )

encode_multipart=False方法的request_encode_body部分解决了我的问题。