반응형
이 기능에 갇혀 있습니다.
def send_request_json(self, request):
url = request
req = urllib.request.Request(url=url)
req.add_header('Accept', 'application/json')
try:
return json.load(urllib.request.urlopen(req))
except ValueError:
return False
이에 도달하면 json은 다음과 같이 응답합니다.
TypeError: the JSON object must be str, not 'bytes'
몇 군데에서 json.load
에 대해 .read ()
와 함께 객체 (이 경우 HTTPResponse
객체)를 전달해야한다고 읽었습니다. 첨부되었지만 HTTPResponse
개체에서는 작동하지 않습니다.
다음에 이것으로 어디로 가야할지 모르겠지만 1500 줄 스크립트 전체가 Python 3으로 새로 변환되었으므로 2.7로 돌아가고 싶지 않습니다.
해결 방법
최근에 Nexmo 메시지를 보내는 작은 함수를 작성했습니다. libpynexmo 코드의 전체 기능이 필요하지 않은 경우이 작업을 수행해야합니다. libpynexmo를 계속해서 점검하려면이 코드를 복사하십시오. 핵심은 utf8 인코딩입니다.
def nexmo_sendsms(api_key, api_secret, sender, receiver, body):
"""
Sends a message using Nexmo.
:param api_key: Nexmo provided api key
:param api_secret: Nexmo provided secrety key
:param sender: The number used to send the message
:param receiver: The number the message is addressed to
:param body: The message body
:return: Returns the msgid received back from Nexmo after message has been sent.
"""
msg = {
'api_key': api_key,
'api_secret': api_secret,
'from': sender,
'to': receiver,
'text': body
}
nexmo_url = 'https://rest.nexmo.com/sms/json'
data = urllib.parse.urlencode(msg)
binary_data = data.encode('utf8')
req = urllib.request.Request(nexmo_url, binary_data)
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
return result['messages'][0]['message-id']
참조 페이지 https://stackoverflow.com/questions/24069197
반응형
'파이썬' 카테고리의 다른 글
파이썬 qtableWidget PyQT에 행을 추가하는 방법은 무엇입니까? (0) | 2020.12.13 |
---|---|
파이썬 기본 동작을 중단하지 않고 Python에서 __getattr__을 어떻게 재정의합니까? (0) | 2020.12.13 |
파이썬 Python 오류 : +에 대해 지원되지 않는 피연산자 유형 : 'int'및 'NoneType' (0) | 2020.12.13 |
파이썬 pyvenv-3.4 returned non-zero exit status 1 (0) | 2020.12.13 |
파이썬 URL에서 Python 객체로 XML 구문 분석 (0) | 2020.12.13 |
댓글