Asynchronous User Data Fetching from randomuser.me API

  • Share this:

Code introduction


This code defines an asynchronous function xxx that fetches random user information from the randomuser.me API. It first creates an asynchronous event loop, then calls the get_random_user_info function to asynchronously retrieve data, and finally returns the user information.


Technology Stack : Aiohttp-web, asyncio

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import aiohttp
import asyncio
import random

async def fetch_random_user_data(session):
    url = 'https://randomuser.me/api/'
    async with session.get(url) as response:
        return await response.json()

async def get_random_user_info():
    async with aiohttp.ClientSession() as session:
        data = await fetch_random_user_data(session)
        return data['results'][0]

def xxx():
    loop = asyncio.get_event_loop()
    user_info = loop.run_until_complete(get_random_user_info())
    return user_info