Asenkron işleme

FastAPI ile Üretime AI Dağıtımı

Matt Eckerle

Software and Data Engineering Leader

Asenkron işleme nedir

Bir masada oturana içecek servis eden biri

 

Birden çok isteği eşzamanlı ele almayı sağlar

FastAPI ile Üretime AI Dağıtımı

Senkron vs asenkron istekler

Senkron ve asenkron isteklerde işlem sürelerinin farkını gösteren bir grafik

FastAPI ile Üretime AI Dağıtımı

Senkron uç noktaları asenkrona dönüştürme

 

@app.post("/analyze")
def analyze_sync(comment: Comment):
    result = sentiment_model(comment.text)
    return {"sentiment": result}

 

import asyncio

@app.post("/analyze")
async def analyze_async(comment: Comment):
    result = await asyncio.to_thread(
        sentiment_model, comment.text
    )
    return {"sentiment": result}
FastAPI ile Üretime AI Dağıtımı

Arka plan görevleri uygulama

from fastapi import BackgroundTasks
from typing import List
@app.post("/analyze_batch")
async def analyze_batch(
    comments: Comments,
    background_tasks: BackgroundTasks
):
    async def process_comments(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(
              sentiment_model, text)
    background_tasks.add_task(process_comments, 
                              comments.texts)
    return {"message": "Processing started"}
  • BackgroundTasks, yorum işleme kuyruğunu yönetir

 

  • background_tasks, yanıttan sonraki işlemleri ele alır.

 

  • add_task, process_comments görevini asenkron planlar.
FastAPI ile Üretime AI Dağıtımı

Hata yönetimi ekleme

@app.post("/analyze_comment")
async def analyze_comment(comment: Comment):
    try:
        sentiment_model = SentimentAnalyzer()
        result = await asyncio.wait_for(
            sentiment_model(comment.text),
            timeout=5.0
        )
        return {"sentiment": result["label"]}
FastAPI ile Üretime AI Dağıtımı

Hata yönetimi ekleme

    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=408,
            detail="Analysis timed out"
        )
    except Exception:
        raise HTTPException(
            status_code=500,
            detail="Analysis failed"
        )
FastAPI ile Üretime AI Dağıtımı

Hadi pratik yapalım!

FastAPI ile Üretime AI Dağıtımı

Preparing Video For Download...