xennygrimmato / fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
https://fastapi.tiangolo.com/
MIT License
0 stars 0 forks source link

Make it easy to use custom `APIRouter`s #5

Open xennygrimmato opened 6 months ago

xennygrimmato commented 6 months ago

Details

I'm facing a problem when using a custom router becomes a real hack. The current hacky solution:

import redis.asyncio as redis
from fastapi import FastAPI, Depends

from cachepot.constants import CachePolicy
from cachepot.routing import CachedAPIRouter
from cachepot.storages.redis import RedisStorage

app = FastAPI()

app.router = CachedAPIRouter(
    dependency_overrides_provider=app,
    # define dependencies inside overridden router only
    dependencies=(Depends(...),),
)

# hack to finish setting up custom router
app.setup()

client = redis.from_url('redis://127.0.0.1:6379')
storage = RedisStorage(client)

cache_policy = CachePolicy(
    storage=storage,
    key='cached_hello_world',
    ttl=30,
)

# Do not use @app.route() due to incapability
@app.router.get(path='', cache_policy=cache_policy)
async def cached_hello_world():
    return {'result': 'hello, world!'}

As you can see, I have to patch app with a new router using

app.router = CachedAPIRouter()

and then call

app.setup()

to be able to use it. Also, direct

@app.router.get()

call is required because router doesn't support custom params.