Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Your First Async Function | The Asyncio Foundation
Python Asyncio in Depth
Sektion 1. Kapitel 7
single

single

Challenge: Your First Async Function

Stryg for at vise menuen

You are working with the public API jsonplaceholder.typicode.com, which provides fake data for testing and learning. Your task is to fetch user information and display it in a readable format.

The endpoint https://jsonplaceholder.typicode.com/users/{user_id} returns a JSON object with the following fields:

  • name: the user's full name;
  • email: the user's email address;
  • company: an object with a name field containing the company name.
Opgave

Swipe to start coding

  1. Define an async function fetch_user(client, user_id) that:
    • Sends a GET request to the users endpoint using the provided client and user_id;
    • Extracts name, email, and company name from the response;
    • Prints them in the format: Name | Email | Company.
  2. Define an async function main() that:
    • Creates an httpx.AsyncClient;
    • Uses asyncio.gather() to fetch users with IDs 1, 2, and 3 concurrently.
  3. Run main() using asyncio.run().

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 7
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt