Asynchronous User Agent Organization Retrieval

  • Share this:

Code introduction


This function uses the Aiohttp library to perform asynchronous HTTP requests to get the geographic information of the current IP and return the organization name.


Technology Stack : Aiohttp, asyncio, json

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
def random_user_agent():
    import aiohttp
    import asyncio

    async def fetch_user_agent(session):
        async with session.get('https://api.ipify.org') as response:
            ip = await response.text()
            async with session.get(f'https://ipinfo.io/{ip}/geo') as response:
                data = await response.json()
                return data.get('org', 'Unknown')

    async def main():
        async with aiohttp.ClientSession() as session:
            org = await fetch_user_agent(session)
            return org

    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(main())
    return result