Section 2. Chapitre 7
single
Challenge: Fetching Data Concurrently
Glissez pour afficher le menu
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 withnameandemailfields;https://jsonplaceholder.typicode.com/posts?userId={user_id}– returns a list of posts for a given user.
Tâche
Glissez pour commencer à coder
- Define an async function
fetch_user(client, user_id)that fetches the user object and returns a dict with keysnameandemail. - 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. - Define an async function
fetch_user_summary(client, user_id)that:- calls
fetch_user()andfetch_post_count()concurrently usingasyncio.gather(); - returns a formatted string:
"{name} ({email}) – {post_count} posts".
- calls
- Define an async function
main()that:- fetches summaries for user IDs
1through5concurrently usingasyncio.gather(); - prints each summary on a separate line.
- fetches summaries for user IDs
- Run
main()usingasyncio.run().
Solution
Tout était clair ?
Merci pour vos commentaires !
Section 2. Chapitre 7
single
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion