Avsnitt 2. Kapitel 7
single
Challenge: Fetching Data Concurrently
Svep för att visa menyn
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.
Uppgift
Svep för att börja koda
- 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().
Lösning
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 7
single
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal