[Python] Is it possible to use an asynchronous function to get data inside a module that is...

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I am writing a bot on aiogram. Naturally, all my code is asynchronous. I decided to rewrite the filters to the routers.

    Structure:

    main.py
    *others*.py
    routers.py
    users.json
    users.py


    Previously, I just had a variable have_access_ids, in which I stored the ids of users who can use the bot.

    routers.py - old

    have_access_ids = [1]
    router = Router()

    router.message.filter(
    F.from_user.id.in_(have_access_ids)
    )

    router.message.register(cmd, filters)


    Now, I'd like to have have_access_ids generated dynamically. I created users.json, where I added the ids of the users I needed, created a users.py file, where I write asynchronous functions for working with the users.json file. They are working properly.

    users.py

    async def get_users():
    async with aiofiles.open('users.json', 'r') as users:
    content = await users.read()
    users_json = json.loads(content)
    return users_json


    Because of the fact that users.py it has asynchronous functions, I need to rewrite routers.py And I don't understand how I can do it.

    I've only come up with two options:

    1. Inside users.py write a synchronous sync_get_users function and use it to get a list of ids:

    users.py

    def sync_get_users():
    with open('users.json', 'r') as users:
    content = users.read()
    users_json = json.loads(content)
    return users_json


    routers.py

    have_access_ids = []
    router = Router()

    users = sync_get_users()
    have_access_ids = users.copy()

    router.message.filter(
    F.from_user.id.in_(have_access_ids)
    )

    router.message.register(cmd, filters)

    1. Change routers.py as follows:

    have_access_ids = []
    router = Router()

    async def setup_router():
    global have_access_ids
    users = await get_users()
    have_access_ids = users.copy()
    router.message.filter(
    F.from_user.id.in_(have_access_ids)
    )

    asyncio.run(setup_router())

    router.message.register(cmd, filters)


    I don't fully understand which of these options is correct (or both are incorrect). Also, I do not understand, if we go by the second option, whether it is correct to use asyncio.run(), since in main.py I'm already using asyncio.run(). Won't this create problems?

    Please tell me what is the best way to act in this situation?

    I apologize for the vague wording of the question, I just don't fully understand how asynchrony works, because of this I can't formulate my question accurately

    Continue reading...

Compartilhe esta Página