Consider a REST API that processes a batch of tasks asynchronously. The server returns a job ID immediately, and the client polls the job status until completion.
What will be printed by the client code below?
import asyncio async def check_status(job_id): # Simulate job completion after 3 checks for i in range(3): print(f"Checking status for job {job_id}, attempt {i+1}") await asyncio.sleep(0.1) return "completed" async def main(): job_id = "job123" status = await check_status(job_id) print(f"Job {job_id} status: {status}") asyncio.run(main())
Remember that await pauses the function until the awaited coroutine finishes.
The check_status function prints the status check messages sequentially with delays, then returns "completed". The main function awaits this, so all checks print before the final status print.
You want to send a batch of tasks to a REST API that will process them asynchronously. Which HTTP method should you use to submit the batch job?
Think about which method is used to create new resources or submit data.
POST is used to submit data to the server to create a new resource or trigger processing, which fits submitting a batch job.
Look at this client code that polls a batch job status from a REST API. It never stops polling. Why?
import asyncio import random async def get_status(job_id): # Simulate random job status return random.choice(["pending", "pending", "completed"]) async def poll_job(job_id): status = "pending" while status != "completed": status = await get_status(job_id) print(f"Job {job_id} status: {status}") await asyncio.sleep(0.1) asyncio.run(poll_job("job456"))
Look at the probabilities of the status values returned.
Because "pending" is chosen twice as often as "completed", the loop might run many times before completion, but it will eventually stop. However, it can appear to never stop in short runs due to randomness.
Choose the correct Python async function syntax that submits a batch job and returns a job ID string.
Remember the correct order of keywords for async function definitions.
Option C uses the correct syntax: async def function_name():. Option C has wrong keyword order. Option C misses def. Option C uses yield which makes it an async generator, not a normal async function.
This code submits a batch of 5 tasks asynchronously and collects results. How many items will be in the results list after completion?
import asyncio async def process_task(task_id): await asyncio.sleep(0.1) return f"result_{task_id}" async def process_batch(tasks): results = [] for task in tasks: result = await process_task(task) results.append(result) return results batch_tasks = [1, 2, 3, 4, 5] results = asyncio.run(process_batch(batch_tasks)) print(len(results))
Each task is awaited and its result appended to the list.
The code processes each of the 5 tasks sequentially, appending one result per task, so the results list has 5 items.