शुरू करेंमुफ़्त में शुरू करें

Background tasks लागू करना

आपकी sentiment analysis API को एक ही बार में सैकड़ों रिव्यू के बैच प्रोसेस करने के अनुरोध मिल रहे हैं. यूज़र्स को इंतज़ार कराए बिना इसे कुशलता से संभालने के लिए, आप background task प्रोसेसिंग लागू करेंगे ताकि क्लाइंट को प्रतिक्रिया भेजने के बाद भी अनुरोधों का प्रोसेस जारी रह सके.

यह अभ्यास पाठ्यक्रम का हिस्सा है

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

पाठ्यक्रम देखें

अभ्यास निर्देश

  • fastapi से background task क्लास इम्पोर्ट करें.
  • रिक्वेस्ट को बैकग्राउंड में चलने वाले टास्क के रूप में संभालने के लिए background_tasks पैरामीटर घोषित करें.
  • रिव्यू के टेक्स्ट का विश्लेषण करने वाले प्रोसेसिंग टास्क को process_reviews फंक्शन के जरिए शेड्यूल करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

# Import the background task class
from fastapi import ____
# Create a background task dependency
@app.post("/analyze_batch")
async def analyze_batch(
    reviews: Reviews,
    background_tasks: ____
):
    async def process_reviews(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(sentiment_model, text)
            print(f"Processed: {result[0]['label']}")
    # Add the task of analysing reviews' texts to the background
    background_tasks.____(process_reviews, reviews.texts)
    return {"message": "Processing started"}
कोड संपादित करें और चलाएँ