BaşlayınÜcretsiz başlayın

Create an async sentiment analysis endpoint

You're building a social media analytics platform that needs to analyze reviews for sentiment. To handle high traffic efficiently, you need to implement an async endpoint. The sentiment analysis model is already loaded and available as sentiment_model.

Bu egzersiz, kursun bir parçasıdır

Deploying AI into Production with FastAPI

Kursa Göz Atın

Egzersiz talimatları

  • Create an asynchronous POST endpoint /analyze using FastAPI app.
  • Add the keyword to call the sentiment_model asynchronously without blocking other operations.
  • Run the sentiment_model in a separate thread with the review's text, ensuring it doesn't block the event loop.

Uygulamalı etkileşimli egzersiz

Bu egzersizi bu örnek kodu tamamlayarak deneyin.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Review(BaseModel):
    text: str

# Create async endpoint at /analyze route
@app.post("____")
# Write an asynchronous function to process review's text
____ def analyze_review(review: Review):
    # Run the model in a separate thread to avoid any event loop blockage
    result = ____ asyncio.____(sentiment_model, ____)
    return {"sentiment": result[0]["label"]}
Kodu Düzenle ve Çalıştır