Well, I expected to have the sesseion to save cookies.
in my case with imeon inverter, I create session, login to IMEON with session.post() request succesfully, but when in next step I try to read IMEON values with session.get() it responds with login sceen (which means session cookies were not present).
So I thought I with this example I am checking if session cookies are saved. but s.cookie_jar is empty.
I think you have to call update_cookies to set the cookie after successfully logging in.
The client session should have a cookie_jar and things should work out of the box.
Maybe there is some other issue? Can you reproduce the issue with a simple asnycio script?
async def test():
async with aiohttp.ClientSession() as session:
await session.post(...)
await session.get(...)
asyncio.run(test())
So I tested with manual cookie handling with aiohttp and this code works.
But how I do implement in with habapp?
import asyncio
import aiohttp
import json
from http.cookies import SimpleCookie
from yarl import URL
async def test():
payload = {
'do_login': 'true',
'email': "****",
'passwd': "****"
}
async with aiohttp.ClientSession() as session:
r = await session.post('http://*.*.*.*/login', data=payload)
# Print response and headers to verify cookies are being set
print(f"result of call: {r}")
response_json = await r.json()
print(response_json)
print(f"Response headers: {r.headers}")
# Manually parse the Set-Cookie headers
set_cookie_headers = r.headers.getall('Set-Cookie', [])
cookie_jar = SimpleCookie()
for header in set_cookie_headers:
cookie_jar.load(header)
# Debug: Print parsed cookies
print("Parsed cookies from Set-Cookie headers:")
cookies = {}
for key, morsel in cookie_jar.items():
cookies[key] = morsel.value
print(f"cookie: {key}, value: {morsel.value}")
# Perform an authorized GET request with the manually set cookies
async with session.get('http://*.*.*.*/data', cookies=cookies, timeout=10) as r:
r.raise_for_status()
print(f"IMEON READ data status: {r.status}")
if 'application/json' in r.headers.get('Content-Type', ''):
json_data = await r.json()
print(json_data)
if r.status != 200:
print("!200")
else:
response_text = await r.text()
print(f"Unexpected response content type: {r.headers.get('Content-Type')}")
print(f"Response content: {response_text}")
asyncio.run(test())
import asyncio
import logging
from http.cookies import SimpleCookie
from yarl import URL
import HABApp
class AsyncRule2(HABApp.Rule):
def __init__(self):
super().__init__()
self.log = logging.getLogger(f"Rule.{self.__class__.__name__}")
self.run.soon(self.async_func)
async def async_func(self):
payload = {
'do_login': 'true',
'email': "****",
'passwd': "****"
}
async with self.async_http.get_client_session() as session:
r = await session.post('http://10.0.20.201/login', data=payload)
# self.log.debug response and headers to verify cookies are being set
self.log.debug(f"result of call: {r}")
response_json = await r.json()
self.log.debug(response_json)
self.log.debug(f"Response headers: {r.headers}")
# Manually parse the Set-Cookie headers
set_cookie_headers = r.headers.getall('Set-Cookie', [])
cookie_jar = SimpleCookie()
for header in set_cookie_headers:
cookie_jar.load(header)
# Debug: self.log.debug parsed cookies
self.log.debug("Parsed cookies from Set-Cookie headers:")
cookies = {}
for key, morsel in cookie_jar.items():
cookies[key] = morsel.value
self.log.debug(f"cookie: {key}, value: {morsel.value}")
# Perform an authorized GET request with the manually set cookies
async with session.get('http://10.0.20.201/data', cookies=cookies, timeout=10) as r:
r.raise_for_status()
self.log.debug(f"IMEON READ data status: {r.status}")
if 'application/json' in r.headers.get('Content-Type', ''):
json_data = await r.json()
self.log.debug(json_data)
if r.status != 200:
self.log.debug("!200")
else:
response_text = await r.text()
self.log.debug(f"Unexpected response content type: {r.headers.get('Content-Type')}")
self.log.debug(f"Response content: {response_text}")
AsyncRule2()
it does not need to restart habapp to work properly.
So all in all, mo code now works perfectly with cookies extraction and writing code. I do not not know if malfunction of automatic ClientSession cookies management implementation was specific to my circumstances.
@Spaceman_Spiff , thanks a lot for you help, it was most useful. And HabAPP for me is super useful.
I would have worked without moving to the init block.
The context manager (with ... as session) closed the existing session that’s why you had to do the restart once (so you have an open session which you can use again).
When in doubt you can also create the rule with the async function from your test script.
You will then create a session each time which is not optimal, but tbh for some home automation stuff which runs once a couple of minutes it doesn’t really matter.