Hataları yönetme

FastAPI'ye Giriş

Matt Eckerle

Software and Data Leader

Hata Yönetiminin İki Ana Nedeni

Kullanıcı hatası

  • Geçersiz veya eski URI
  • Eksik ya da hatalı girdi
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Return an error
    else:
        crud.delete_item(item)
        return {}

Sunucu hatası

  • Başka bir sorun oluştu
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
FastAPI'ye Giriş

HTTP Durum Kodları: “Bağırma Seviyeleri”

  • API'nin yanıtta durum iletmesini sağlar
    • Başarı, başarısızlık, hata vb.
  • HTTP protokolünde tanımlı özel kodlar
  • Aralık: 100 - 599
  • İlk rakama göre sınıflandırılır (1 -5)
  1. Bilgilendirme yanıtları (100 - 199)
  2. Başarılı yanıtlar (200 - 299)
  3. Yönlendirme iletileri (300 - 399)
  4. İstemci hatası yanıtları (400 - 499)
  5. Sunucu hatası yanıtları (500 - 599)
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
FastAPI'ye Giriş

Yaygın HTTP Durum Kodları

Başarı (200 - 299)

  • 200 OK
    • Varsayılan başarı yanıtı
  • 201 Created
    • POST işlemine özgü
  • 202 Accepted
    • Kesin değil. “Üzerinde çalışılıyor”
  • 204 No Content
    • Başarılı! Ek içerik yok

Diğer yanıtlar

  • 301 Moved Permantently
    • URI kalıcı olarak değişti
  • 400 Bad Request
    • İstemci hatası
  • 404 Not Found
    • Sunucu istenen kaynağı bulamıyor
  • 500 Internal Server Error
    • Sunucu ne yapacağını bilmediği bir durumla karşılaştı
FastAPI'ye Giriş

Durum Kodlarıyla Hata Yönetimi

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Send response with status 404 and specific error message
        raise HTTPException(status_code=404, detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}
FastAPI'ye Giriş

Hadi pratik yapalım!

FastAPI'ye Giriş

Preparing Video For Download...