fastadmin icon indicating copy to clipboard operation
fastadmin copied to clipboard

How to get obj asynchronously in "has_xxx_permission" synchronous method

Open coedor01 opened this issue 2 years ago • 2 comments

I can only get objects through asynchronous methods, but this method is a synchronous method. I have no idea how to use this function.

I tried writing the code like this but it doesn't get the result correctly.

async def get_add_permission(self, user_id: UUID | int | None = None) -> bool:
    sessionmaker = self.get_sessionmaker()
    async with sessionmaker() as session:
        user: models.BaseUser = (
            await session.scalars(async_select(models.BaseUser).where(models.BaseUser.id == user_id))).first()
    return user.is_superuser

def has_add_permission(self, user_id: UUID | int | None = None) -> bool:
    loop = asyncio.get_running_loop()
    future = asyncio.run_coroutine_threadsafe(self.get_add_permission(user_id), loop)
    result = future.result()
    return result

Can someone tell me how to solve this problem, thanks!

coedor01 avatar Jul 05 '23 07:07 coedor01

"has_xxx_permission" is a method of "BaseModelAdmin" class

coedor01 avatar Jul 05 '23 07:07 coedor01

Try to use async_to_sync function Ofc you need to install pip install asgiref

from asgiref.sync import async_to_sync

@async_to_sync
async def get_add_permission(...):

Or

from asgiref.sync import async_to_sync

res = async_to_sync(get_add_permission(...))

WrldEngine avatar Feb 25 '24 21:02 WrldEngine

thank for your solution, but i no longer user this, i'll close the issue.

coedor01 avatar May 31 '24 12:05 coedor01