azogue / aiopvpc

Simple aio library to download Spanish electricity hourly prices (PVPC) from esios.ree.es
MIT License
41 stars 10 forks source link

Example provided results in error message #67

Closed Eng65745 closed 7 months ago

Eng65745 commented 7 months ago

Hi,

When trying to run (in IDLE under Windows 10) the example provided in READ.cmd it turns out an error message:

import aiohttp from datetime import datetime from aiopvpc import PVPCData async with aiohttp.ClientSession() as session: pvpc_handler = PVPCData(session=session, tariff="2.0TD")

SyntaxError: 'async with' outside async function

Can you please check if there's some mistake in the lines above? (though it doesn't show up, the line pvpc_handler... is properly indented) Thanks !

azogue commented 7 months ago

Hi @Eng65745,

To run an isolated piece of async code you need to invoke it with asyncio.run:

import asyncio
import aiohttp
from datetime import datetime
from aiopvpc import PVPCData

async def _show_current_pvpc_prices():
    async with aiohttp.ClientSession() as session:
        pvpc_handler = PVPCData(session=session, tariff="2.0TD")
        esios_data = await pvpc_handler.async_update_all(
            current_data=None, now=datetime.utcnow()
        )
    print(esios_data.sensors["PVPC"])

asyncio.run(_show_current_pvpc_prices())

In jupyter, the code-snippet from the README works without problems, as you can await coroutines in the cells.

For an invocation inside IDLE or as a python script, you'll need to call asyncio.run(coroutine()).

But the code-snippet is meant to just document how the library works, not to be used like that 😅

azogue commented 7 months ago

To run an isolated piece of async code

For more context take a look here: https://realpython.com/async-io-python/

Eng65745 commented 7 months ago

Thanks for the quick answer. I'm a beginner with python, and was just playing around trying to find the esios api (there are quite a few, with different data) that better fits my small project (displaying in a HA dasboard a graph of prices from current time until end of day, or end of next day if after 20:30). Tinkering with the code from advanced developpers helps a lot, even if often I don't fully understand all the code.

Gracias!