fastadmin
fastadmin copied to clipboard
How to get obj asynchronously in "has_xxx_permission" synchronous method
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!
"has_xxx_permission" is a method of "BaseModelAdmin" class
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(...))
thank for your solution, but i no longer user this, i'll close the issue.