Nhập môn FastAPI
Matt Eckerle
Software and Data Engineering Leader


Định nghĩa hàm lấy burger
# Đây không phải bất đồng bộ
def get_sequential_burgers(number: int):
# Làm tuần tự
return burgers
Gọi hàm theo cách tuần tự
burgers = get_burgers(2)
Định nghĩa hàm lấy burger
async def get_burgers(number: int):
# Làm bất đồng bộ
return burgers
Gọi hàm theo cách bất đồng bộ
burgers = await get_burgers(2)
Nếu có thể:
results = await some_library()
Thì dùng async def:
@app.get('/')
async def read_results():
results = await some_library()
return results
Lưu ý Chỉ dùng
awaitbên trong hàm tạo bằngasync def
Khi ứng dụng phải chờ hệ thống khác phản hồi
Ví dụ
Tác vụ nặng CPU
Ví dụ
Khi không chắc chắn
Nhập môn FastAPI