Skip to content
This repository has been archived by the owner on Feb 23, 2020. It is now read-only.

How to pass cache objects between files? #25

Open
florimondmanca opened this issue Nov 19, 2019 · 1 comment
Open

How to pass cache objects between files? #25

florimondmanca opened this issue Nov 19, 2019 · 1 comment
Labels
documentation Improvements or additions to documentation question Further information is requested

Comments

@florimondmanca
Copy link
Owner

@invokermain wrote in #22:

A side question I had which would be nice to have documented: do you have a recommended way of passing cache objects to submodules (e.g. if you have various submodules defining a starlette router and some endpoints), or just around the project in general? Having some more example patterns in the documentation would be great 👍

@florimondmanca florimondmanca added the question Further information is requested label Nov 19, 2019
@florimondmanca
Copy link
Owner Author

florimondmanca commented Nov 19, 2019

I think one possible idiom to use here is a resources.py file where you would declare the cache instance (or multiple instances, e.g. cache_default, cache_special, etc.), and then import it in the various parts of the application:

# project/resources.py
from caches import Cache

cache = Cache("locmem://null")
# project/apps/sub.py
from starlette.routing import Route
from ..resources import cache

async def view(request):
    item = await cache.get("some.key")
    ...

routes = [
    Route("/some/path", view),
]
# project/apps/main.py
from asgi_caches.middleware import CacheMiddleware
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.middleware import Middleware
from ..resources import cache
from . import sub

async def home(request):
    ...

routes = [
    Route("/", home),
    Mount("/sub", routes=sub.routes),
]

middleware = [
    Middleware(CacheMiddleware, cache=cache),
]

app = Starlette(
    routes=routes,
    middleware=middleware,
    on_startup=[cache.connect],
    on_shutdown=[cache.disconnect],
)

(Note that I'm using the Starlette v0.13+ declarative style here.)

@florimondmanca florimondmanca added the documentation Improvements or additions to documentation label Nov 19, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
documentation Improvements or additions to documentation question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant