การใช้ async สำหรับงานพร้อมกัน

FastAPI เบื้องต้น

Matt Eckerle

Software and Data Engineering Leader

ทำไมต้องใช้ async? เบอร์เกอร์แบบพร้อมกัน!

เบอร์เกอร์แบบลำดับ

ลูกค้าต่อคิวรอเบอร์เกอร์ที่เตรียมและเสิร์ฟแบบทีละลำดับ

เบอร์เกอร์แบบพร้อมกัน

ลูกค้าต่อคิวรอเบอร์เกอร์ที่เตรียมและเสิร์ฟแบบพร้อมกัน

1 https://fastapi.tiangolo.com/async/
FastAPI เบื้องต้น

async ในทางปฏิบัติ

เบอร์เกอร์แบบลำดับ

นิยามฟังก์ชันสำหรับสั่งเบอร์เกอร์

# This is not asynchronous
def get_sequential_burgers(number: int):
    # Do some sequential stuff
    return burgers

เรียกฟังก์ชันแบบลำดับ

burgers = get_burgers(2)

เบอร์เกอร์แบบพร้อมกัน

นิยามฟังก์ชันสำหรับสั่งเบอร์เกอร์

async def get_burgers(number: int):
    # Do some asynchronous stuff
    return burgers

เรียกฟังก์ชันแบบอะซิงโครนัส

burgers = await get_burgers(2)
FastAPI เบื้องต้น

FastAPI กับ async

หากสามารถใช้:

results = await some_library()

ให้ใช้ async def:

@app.get('/')
async def read_results():
    results = await some_library()
    return results

หมายเหตุ ใช้ await ได้เฉพาะภายในฟังก์ชันที่สร้างด้วย async def เท่านั้น

FastAPI เบื้องต้น

เมื่อใดควรใช้ async

ใช้ async

เมื่อแอปพลิเคชันต้องรอการตอบสนองจากระบบอื่น

  • External API
  • ฐานข้อมูล

ตัวอย่าง

  • HTTP requests
  • การสืบค้นฐานข้อมูล
  • การอ่านไฟล์

ไม่ควรใช้ async

งานที่ใช้ CPU หนัก

ตัวอย่าง

  • การประมวลผลเสียงหรือรูปภาพ
  • Computer Vision
  • Machine Learning
  • Deep Learning

เมื่อไม่แน่ใจ

FastAPI เบื้องต้น

มาฝึกกันเลย!

FastAPI เบื้องต้น

Preparing Video For Download...