Last active
March 24, 2020 11:01
-
-
Save victorusachev/78534b12dcdeda593d8fd2ab67aab8b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| My solution | |
| See https://t.me/aiohttp_ru/3955 | |
| """ | |
| import asyncio | |
| import json | |
| import aiohttp | |
| from asgiref.sync import sync_to_async | |
| class HttpClient: | |
| endpoints = { | |
| 'user': 'https://jsonplaceholder.typicode.com/users/{id}/', | |
| } | |
| async def __aenter__(self) -> 'HttpClient': | |
| self._session = aiohttp.ClientSession() | |
| return self | |
| async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: | |
| await self._session.close() | |
| async def fetch_user_data_by_id(self, user_id): | |
| url = self.endpoints['user'].format(id=user_id) | |
| async with self._session.get(url) as resp: | |
| return await resp.json() if resp.status == 200 else {} | |
| async def get_user_info_by_id(user_id, http_client=None): | |
| http_client = http_client or HttpClient() # add http_client | |
| async with http_client: | |
| user_info = await http_client.fetch_user_data_by_id(user_id) | |
| return user_info['username'] # change key 'login' -> 'username' | |
| @sync_to_async # decorate | |
| def get_user_login_from_webtoken_data(payload): | |
| subject = json.loads(payload['sub']) | |
| user_id = subject['uid'] | |
| user_login = asyncio.run(get_user_info_by_id(user_id)) | |
| return user_login | |
| def get_user_login_from_sso_data(payload): | |
| return payload['preferred_username'] | |
| # regular function | |
| def get_user_id_from_token_payload(payload): | |
| try: | |
| client_login = get_user_login_from_sso_data(payload) | |
| except KeyError: | |
| # it will create a new loop for every call | |
| client_login = asyncio.run(get_user_login_from_webtoken_data(payload)) | |
| return client_login | |
| if __name__ == '__main__': | |
| async def main(callback): | |
| payload = { | |
| # 'preferred_username': 'superuser', | |
| 'sub': '{"uid": 1}', | |
| } | |
| return await callback(payload) | |
| clb = sync_to_async(get_user_id_from_token_payload) | |
| result = asyncio.run(main(clb)) | |
| print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment