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

single

Challenge: Fetching Data Concurrently

Swipe um das Menü anzuzeigen

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

Wischen, um mit dem Codieren zu beginnen

  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ösung

Switch to desktopWechseln Sie zum Desktop, um in der realen Welt zu übenFahren Sie dort fort, wo Sie sind, indem Sie eine der folgenden Optionen verwenden
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 7
single

single

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt