TypeError: невозможно объединить str в байты в HTTPSConnection - PullRequest
0 голосов
/ 04 августа 2020

Я пытаюсь сделать запрос на авторизацию и получаю TypeError: can't concat str to bytes. Я поискал в Интернете и нашел похожие проблемы, но ни одна из них не помогла решить мою проблему. В настоящее время я работаю в Jupyter (если это поможет?) Также я python новичок, поэтому будьте осторожны ...

Вот мой код:

import http.client as httplib
import urllib.request, urllib.parse, urllib.error, base64
import requests as rq

base_url = 'api/url'
end_point = '/endpoint'
full_url = base_url + end_point

request_body = {
    'UserName':'un',
    'Password':'pw'
}

header = {
    'tenant': 'tenant name'  #required by vendor
}

print(type(base_url))
print(type(end_point))
print(type(full_url))
print(type(request_body))
print(type(header))

try:
    conn = httplib.HTTPSConnection(base_url)
    conn.request(method='POST',url=full_url, body=request_body, headers=header)
    response = conn.getresponse()
    data = response.read()
    print(type(data))
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

Я получаю следующая ошибка:

TypeError: невозможно объединить str в байты

Полная трассировка:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'dict'>
<class 'dict'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-1a19e8736fec> in <module>
     24     conn = httplib.HTTPSConnection(base_url)
---> 25     conn.request(method='POST',url=full_url, body=request_body, headers=header)
     26     response = conn.getresponse()

~\Documents\Anaconda\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
   1243         """Send a complete request to the server."""
-> 1244         self._send_request(method, url, body, headers, encode_chunked)
   1245 

~\Documents\Anaconda\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1289             body = _encode(body, 'body')
-> 1290         self.endheaders(body, encode_chunked=encode_chunked)
   1291 

~\Documents\Anaconda\lib\http\client.py in endheaders(self, message_body, encode_chunked)
   1238             raise CannotSendHeader()
-> 1239         self._send_output(message_body, encode_chunked=encode_chunked)
   1240 

~\Documents\Anaconda\lib\http\client.py in _send_output(self, message_body, encode_chunked)
   1063                     chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
-> 1064                         + b'\r\n'
   1065                 self.send(chunk)

TypeError: can't concat str to bytes

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-24-1a19e8736fec> in <module>
     30     conn.close()
     31 except Exception as e:
---> 32     print("[Errno {0}] {1}".format(e.errno, e.strerror))

AttributeError: 'TypeError' object has no attribute 'errno'

Что мне здесь не хватает? Что я не понимаю?

Ответы [ 2 ]

2 голосов
/ 04 августа 2020

Я думаю, что эта ошибка вызвана body=request_body в методе request.

conn.request(method='POST',url=full_url, body=request_body, headers=header)

Из документации

body может быть str, байтовым объектом, открытым файловым объектом или итерацией байтов.

Но в этом случае request_body - это объект dict. Поэтому преобразование в JSON, вероятно, решит эту проблему.

import json

conn.request(method='POST',url=full_url, body=json.dumps(request_body), headers=header)
0 голосов
/ 04 августа 2020
NameError                                 Traceback (most recent call last)
<ipython-input-3-75a4126e3e42> in <module>
     19 print(type(end_point))
     20 print(type(full_url))
---> 21 print(type(body_info))
     22 print(type(header))
     23 

NameError: name 'body_info' is not defined

Вы забыли определить body_info или, скорее всего, определили его как request_body и не помните.

Достаточно исправить эту строку:

body_info = {
    'UserName':'un',
    'Password':'pw'
}

вместо названия словаря request_body

...