edihasaj / tuspy-fast-api

MIT License
20 stars 9 forks source link

Dependency injection in callback #11

Open christoe opened 1 year ago

christoe commented 1 year ago

Hi,

I'm trying to integrate this library into an already existing FastAPI application. This application we're trying to build with FastAPI best practices and using dependency injection (Depends()). We need to do some validation and post processing after a file upload, that requires us to call a lot of functions in the application used by other routes. What I've realised is, that it's not possible to call functions with dependencies from the callback, since the callback function itself is not depended upon. But depending on it makes it run prior to the route calling it, which is not what we want either. Have you given any thought to this, or have an idea on how to solve it?

Thanks!

edihasaj commented 1 year ago

Then I think, I will have to do a check and make some changes to wrap it on a class if it doesn't work like that. I think we can require optional with Depends and if you don't pass it it should be good, but I have to run some checks and get back at you

edihasaj commented 1 year ago

@christoe can we try something like this:

from fastapi import Depends, FastAPI
from fastapi.routing import APIRoute

def resolve_dependency(app: FastAPI, dependency: Callable):
    # Mock a fake route to resolve the dependency
    async def temp_route():
        pass

    route = APIRoute("/", temp_route)
    route.dependant.dependencies.append(Depends(dependency))
    app.router.routes.append(route)
    values, *_ = app.router.resolve({"path": {}})
    return values[dependency]
def on_upload_complete(file_path: str):
    # Resolve dependencies
    some_dependency_instance = resolve_dependency(app, some_dependency)

    # Do something with the resolved dependency
    result = some_dependency_instance.some_method()

    print('Upload complete')
    print(file_path, result)
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles

from tusserver.tus import create_api_router

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_methods=["*"],
    allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")

# Rest of your app code ...

# Don't forget to remove the temporary route after using it
app.router.routes = [route for route in app.router.routes if route.path != "/"]

?