Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Help - error when using Aiohttp with headers #414

Answered by devachnid
devachnid asked this question in Q&A
Discussion options

Firstly an apology: I'm new to Python so could be making a very silyl mistake here!

This code works as expected (I get a 401 Unauthorized response as I haven't sent the required authentication via headers)

import time
import hashlib
import hmac
import base64
import aiohttp
@service
def switch_bot_API(action=None, id=None):
 # open token
 token = '123456789' # copy and paste from the SwitchBot app V6.14 or later
 # secret key
 secret = 'abcdef' # copy and paste from the SwitchBot app V6.14 or later
 nonce = ''
 t = int(round(time.time() * 1000))
 string_to_sign = '{}{}{}'.format(token, t, nonce)
 string_to_sign = bytes(string_to_sign, 'utf-8')
 secret = bytes(secret, 'utf-8')
 sign = base64.b64encode(hmac.new(secret, msg=string_to_sign, digestmod=hashlib.sha256).digest())
 header = {
 'Authorization': token, 
 'sign': sign, 
 't': t, 
 'nonce': nonce
 }
 get_url = 'https://api.switch-bot.com/v1.1/devices'
 async with aiohttp.ClientSession() as session:
 async with session.get(url=get_url) as response:
 log.info(f"status {response.status}")
 text = response.text()
 log.info(f"text {text}")

If I change

 async with aiohttp.ClientSession() as session:
 async with session.get(url=get_url) as response:
 log.info(f"status {response.status}")
 text = response.text()
 log.info(f"text {text}")

to (adding the headers to the ClientSession object)

 async with aiohttp.ClientSession(headers=header) as session:
 async with session.get(url=get_url) as response:
 log.info(f"status {response.status}")
 text = response.text()
 log.info(f"text {text}")

The script doesn't work, I get the following error

2022年12月28日 22:17:12.109 ERROR (MainThread) [custom_components.pyscript.file.switchbot.switch_bot_API] Exception in <file.switchbot.switch_bot_API> line 35:
 async with session.get(url=get_url) as response:
 ^
AttributeError: '_RequestContextManager' object has no attribute '_resp'

Google isn't helping me solve this - can anyone here help please?

You must be logged in to vote

SOLVED!

In case anyone else comes across this I solved it by running the script in Python directly, which showed the true underlying error:

Traceback (most recent call last):
 File "/root/switchbot.py", line 47, in <module>
 loop.run_until_complete(main())
 File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
 return future.result()
 File "/root/switchbot.py", line 40, in main
 async with session.get(url=get_url) as response:
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/client.py", line 1141, in __aenter__
 self._resp = await self._coro
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/client.py", line 558, in _request
 resp = ...

Replies: 2 comments

Comment options

SOLVED!

In case anyone else comes across this I solved it by running the script in Python directly, which showed the true underlying error:

Traceback (most recent call last):
 File "/root/switchbot.py", line 47, in <module>
 loop.run_until_complete(main())
 File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
 return future.result()
 File "/root/switchbot.py", line 40, in main
 async with session.get(url=get_url) as response:
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/client.py", line 1141, in __aenter__
 self._resp = await self._coro
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/client.py", line 558, in _request
 resp = await req.send(conn)
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/client_reqrep.py", line 670, in send
 await writer.write_headers(status_line, self.headers)
 File "/usr/local/lib/python3.9/dist-packages/aiohttp/http_writer.py", line 130, in write_headers
 buf = _serialize_headers(status_line, headers)
 File "aiohttp/_http_writer.pyx", line 132, in aiohttp._http_writer._serialize_headers
 File "aiohttp/_http_writer.pyx", line 109, in aiohttp._http_writer.to_str
TypeError: Cannot serialize non-str key b'anK+rbN/+dI5+IlSYizquwB1MT/2JhtnMneDHvadDyU='

The solution was to cast the variables I was using in the headers to strings.

You must be logged in to vote
0 replies
Answer selected by devachnid
Comment options

Good detective work. Unfortunately the error reporting in pyscript isn't always accurate or complete.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /