Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Last active March 12, 2024 11:18
Show Gist options
  • Save Tishka17/9b2625753c80681e8ba688c84d834bb6 to your computer and use it in GitHub Desktop.
Save Tishka17/9b2625753c80681e8ba688c84d834bb6 to your computer and use it in GitHub Desktop.
Fastpi Depends Stub

This Stub class is designed as a workaround for Fastapi Depends which mixes IoC-Container features with request parsing.

You can use parametrized Stub instance to declare dependency whilst not show your class'es __init__ params in OpenAPI specification.

from fastapi import FastAPI, APIRouter, Depends
from stub import Stub
app = FastAPI()
router = APIRouter()
class Repo:
def __init__(self, a: int):
self.a = a
@app.get("/")
async def root(repo: Repo = Depends(Stub(Repo))) -> int:
return repo.a
@app.get("/1")
async def root(repo: Repo = Depends(Stub(Repo, key="1"))) -> int:
return repo.a
app.dependency_overrides[Repo] = lambda: Repo(0)
app.dependency_overrides[Stub(Repo, key="1")] = lambda: Repo(1)
from typing import Callable
class Stub:
def __init__(self, dependency: Callable, **kwargs):
self._dependency = dependency
self._kwargs = kwargs
def __call__(self):
raise NotImplementedError
def __eq__(self, other) -> bool:
if isinstance(other, Stub):
return (
self._dependency == other._dependency
and self._kwargs == other._kwargs
)
else:
if not self._kwargs:
return self._dependency == other
return False
def __hash__(self):
if not self._kwargs:
return hash(self._dependency)
serial = (
self._dependency,
*self._kwargs.items(),
)
return hash(serial)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment