클래스 기반 및 Yield 의존성
클래스를 사용하여 더 복잡한 의존성을 만들고 `yield`로 설정 및 정리 로직을 포함한 리소스를 관리하는 방법을 배웁니다.
클래스 기반 및 Yield 의존성은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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
MyClasshas a__call__method, it will call it and use the returned value as the dependency. - Otherwise, it will use the instance of
MyClassitself 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 (afteryield, often in afinallyblock).
These patterns make your FastAPI applications more robust, maintainable, and easier to test.
자주 묻는 질문
“클래스 기반 및 Yield 의존성” 강의는 무료인가요?
네 — “클래스 기반 및 Yield 의존성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“클래스 기반 및 Yield 의존성”에서 뭘 배우나요?
클래스를 사용하여 더 복잡한 의존성을 만들고 `yield`로 설정 및 정리 로직을 포함한 리소스를 관리하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“클래스 기반 및 Yield 의존성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- FastAPI 의존성 이해하기
- 공통 의존성 주입
- 클래스 기반 및 Yield 의존성
- 전역 종속성과 하위 종속성