Sezione 2. Capitolo 7
single
Challenge: Fetching Data Concurrently
Scorri per mostrare il 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.
Compito
Scorri per iniziare a programmare
- 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().
Soluzione
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 2. Capitolo 7
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione