Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Fetching Data Concurrently | Tasks and Scheduling
Python Asyncio in Depth
Seksjon 2. Kapittel 7
single

single

Challenge: Fetching Data Concurrently

Sveip for å vise menyen

You are building a data aggregation script that pulls information about users and their posts from jsonplaceholder.typicode.com. Your goal is to fetch all the data concurrently and produce a summary report.

The following endpoints are available:

  • https://jsonplaceholder.typicode.com/users/{user_id} – returns a user object with name and email fields;
  • https://jsonplaceholder.typicode.com/posts?userId={user_id} – returns a list of posts for a given user.
Oppgave

Sveip for å begynne å kode

  1. Define an async function fetch_user(client, user_id) that fetches the user object and returns a dict with keys name and email.
  2. Define an async function fetch_post_count(client, user_id) that fetches the posts list for a user and returns the number of posts as an integer.
  3. Define an async function fetch_user_summary(client, user_id) that:
    • calls fetch_user() and fetch_post_count() concurrently using asyncio.gather();
    • returns a formatted string: "{name} ({email}) – {post_count} posts".
  4. Define an async function main() that:
    • fetches summaries for user IDs 1 through 5 concurrently using asyncio.gather();
    • prints each summary on a separate line.
  5. Run main() using asyncio.run().

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 7
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt