Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Fetching Data Concurrently | Tasks and Scheduling
Python Asyncio in Depth
Sección 2. Capítulo 7
single

single

Challenge: Fetching Data Concurrently

Desliza para mostrar el menú

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.
Tarea

Desliza para comenzar a programar

  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().

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 7
single

single

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt