0Pricing
FastAPI Backend Development Bootcamp · Lekcja

Zależności oparte na klasach i yield

Nauczą się Państwo tworzyć bardziej złożone zależności za pomocą klas oraz zarządzać zasobami przy użyciu `yield` w logice konfiguracji i sprzątania.

Zależności oparte na klasach i yield to bezpłatna lekcja FastAPI Backend Development Bootcamp na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej FastAPI Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Beyond Simple Function Dependencies

In previous lessons, we learned about basic function-based dependencies in FastAPI. These are great for simple tasks like validation or injecting common values.

But what if your dependency needs to maintain state, accept configuration, or manage resources that require both setup and cleanup? That's where class-based and yield dependencies come in!

Why Use Class-Based Dependencies?

Class-based dependencies offer several advantages for more complex scenarios:

  • Organization: Encapsulate related logic and data within a class.
  • State: Classes can hold internal state, which can be useful (though be mindful of request isolation).
  • Configuration: Easily pass parameters to the dependency during its instantiation.
  • Testability: Easier to mock or inject specific class instances for testing.

Defining a Class Dependency

To create a class-based dependency, you define a Python class. FastAPI can then use an instance of this class. If your class has a __call__ method, FastAPI will invoke it to get the dependency's value.

Let's see a simple example:

class MyService:
    def __init__(self):
        self.message = "Welcome from MyService!"

    def __call__(self):
        # This method is called by FastAPI to get the value
        return self.message

# Simulate FastAPI's usage:
# FastAPI would instantiate MyService() once or per request
service_instance = MyService()

# It then calls the __call__ method to get the value
dependency_value = service_instance()
print(dependency_value)

How FastAPI Handles Class Dependencies

When you use Depends(MyClass), FastAPI will:

  • Create an instance of MyClass.
  • If MyClass has a __call__ method, it will call it and use the returned value as the dependency.
  • Otherwise, it will use the instance of MyClass itself as the dependency.

If you use Depends(MyClass()), you're passing an already instantiated object, and FastAPI will simply use that object (and its __call__ method if present).

Class Dependencies with Parameters

A major benefit of class-based dependencies is the ability to pass parameters to their constructor. This is perfect for injecting configuration or other dependencies into your service class.

Imagine a service that needs an API key:

class ExternalApiService:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.external.com"

    def __call__(self):
        return f"API Service configured with key: {self.api_key}"

# In a real FastAPI app, the api_key might come from
# an environment variable or another dependency.
# Here, we simulate instantiation with different keys.

prod_api = ExternalApiService(api_key="prod_secret_123")
dev_api = ExternalApiService(api_key="dev_test_abc")

print(prod_api())
print(dev_api())

Introducing Yield Dependencies

Some resources, like database connections or file handlers, need not only to be set up but also properly cleaned up afterwards. This is where yield dependencies shine!

A yield dependency is a generator function that allows you to run code before the endpoint is executed (setup) and after the response is sent (teardown).

Yield for Resource Setup

The code before the yield statement in your dependency function is executed as setup logic. The value that is yielded is what your endpoint function will receive as a dependency.

def get_database_session():
    print("DB: Establishing connection...") # Setup logic
    db_session = {"id": 1, "status": "active"} # Simulate a session
    yield db_session # This value is passed to the dependent function
    # Teardown logic (after yield) would go here

# Simulate a function that uses the dependency
def process_data(session):
    print(f"Endpoint: Processing data with session ID: {session['id']}")

# How FastAPI conceptually uses it:
# 1. Calls get_database_session()
# 2. Takes the yielded value
# 3. Passes it to process_data()

session_generator = get_database_session()
active_session = next(session_generator) # Runs setup, gets yielded value
process_data(active_session)
# FastAPI would then ensure the generator is closed, triggering teardown.

Yield for Resource Teardown

The power of yield dependencies is in their ability to perform cleanup. Any code placed after the yield statement will execute once the request has finished and the response has been sent.

This is typically done within a try...finally block to guarantee cleanup, even if errors occur.

def get_file_handle():
    print("File: Opening 'log.txt'...")
    file_handle = open("log.txt", "w") # Simulate opening a file
    try:
        yield file_handle # Provide the file handle
    finally:
        print("File: Closing 'log.txt'.")
        file_handle.close() # Teardown logic: close the file

# Simulate a function using the dependency
def write_log(f_handle):
    f_handle.write("Lesson content generated.\n")
    print("Endpoint: Wrote to log file.")

# Manual simulation of FastAPI's lifecycle:
file_generator = get_file_handle()
current_file = next(file_generator) # Setup runs
write_log(current_file)

# This step would be handled by FastAPI to trigger teardown
try:
    next(file_generator) # Continues generator, runs finally block
except StopIteration:
    print("Generator exhausted, teardown complete.")

Combining Class-based & Yield Dependencies

You can use both class-based and yield dependencies together! For instance, a class-based dependency might provide configuration for a database, and a yield dependency would then use that configuration to establish and close a database connection.

This allows for highly modular and robust resource management within your FastAPI application.

Quick Check

Consider the benefits and use cases for advanced dependency injection patterns.

Lesson Summary

Great job! In this lesson, you've leveled up your understanding of FastAPI dependencies.

  • Class-based dependencies help organize complex logic, maintain state, and accept configuration.
  • Yield dependencies (generator functions) are powerful for managing resources that require both setup (before yield) and guaranteed teardown (after yield, often in a finally block).

These patterns make your FastAPI applications more robust, maintainable, and easier to test.

Często zadawane pytania

Czy lekcja „Zależności oparte na klasach i yield” jest bezpłatna?

Tak — pełny tekst „Zależności oparte na klasach i yield” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu FastAPI Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Co nauczysz się w „Zależności oparte na klasach i yield”?

Nauczą się Państwo tworzyć bardziej złożone zależności za pomocą klas oraz zarządzać zasobami przy użyciu `yield` w logice konfiguracji i sprzątania. Ćwiczysz FastAPI Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć FastAPI Backend Development Bootcamp?

Nie wymagamy żadnego doświadczenia. FastAPI Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Zależności oparte na klasach i yield”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji FastAPI Backend Development Bootcamp?

Tak. Każda lekcja FastAPI Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zależności w FastAPI
  2. Wstrzykiwanie typowych zależności
  3. Zależności oparte na klasach i yield
  4. Globalne zależności i zależności podrzędne
← Powrót do FastAPI Backend Development Bootcamp