예제 #1
0
def build_application(
    cache_type="memory",
    key_pattern=DEFAULT_KEY_PATTERN,
    encrypt_key=True,
) -> web.Application:
    app = web.Application()
    if cache_type == "memory":
        setup_cache(
            app,
            key_pattern=key_pattern,
            encrypt_key=encrypt_key,
        )
    elif cache_type == "redis":
        url = yarl.URL(env.str("CACHE_URL",
                               default="redis://localhost:6379/0"))
        redis_config = RedisConfig(db=int(url.path[1:]),
                                   host=url.host,
                                   port=url.port)
        setup_cache(
            app,
            cache_type=cache_type,
            backend_config=redis_config,
            key_pattern=key_pattern,
            encrypt_key=encrypt_key,
        )
    else:
        raise ValueError("cache_type should be `memory` or `redis`")
    app.router.add_post("/", some_long_running_view)
    return app
예제 #2
0
def setup_redis(app: web.Application, config_redis: dict):
    setup_cache(app,
                cache_type="redis",
                backend_config=RedisConfig(host=config_redis.get(
                    'host', 'localhost'),
                                           port=config_redis.get('port',
                                                                 6379)))
예제 #3
0
def setup_cache(
    app: web.Application,
    cache_type: str = "memory",
    key_pattern: Tuple[AvailableKeys, ...] = DEFAULT_KEY_PATTERN,
    encrypt_key: bool = True,
    backend_config: bool = None,
) -> None:
    app.middlewares.append(cache_middleware)

    _cache_backend: Optional[Union[MemoryCache, RedisCache]] = None
    if cache_type.lower() == "memory":
        _cache_backend = MemoryCache(key_pattern=key_pattern,
                                     encrypt_key=encrypt_key)

        log.debug("Selected cache: {}".format(cache_type.upper()))

    elif cache_type.lower() == "redis":
        _redis_config = backend_config or RedisConfig()

        if not isinstance(_redis_config, RedisConfig):
            raise AssertionError(f"Config must be a RedisConfig object. Got: "
                                 f"'{type(_redis_config)}'")
        _cache_backend = RedisCache(
            config=_redis_config,
            key_pattern=key_pattern,
            encrypt_key=encrypt_key,
        )

        log.debug("Selected cache: {}".format(cache_type.upper()))
    else:
        raise HTTPCache("Invalid cache type selected")

    app["cache"] = _cache_backend
예제 #4
0
async def init_cache(app):
    conf = app['config']['cache']
    redis_config = RedisConfig(host=conf['host'],
                               port=conf['port'],
                               db=conf['db'],
                               password=conf['password'],
                               key_prefix=conf['key_prefix'])
    await setup_cache(app, cache_type="redis", backend_config=redis_config)
예제 #5
0
from aiohttp import web

if __name__ == '__main__':
    import os
    import sys

    parent_dir = os.path.dirname(
        os.path.dirname(os.path.join("..", os.path.abspath(__file__))))
    sys.path.insert(1, parent_dir)
    import aiohttp_cache

    __package__ = str("aiohttp_cache")

    from aiohttp_cache import cache, setup_cache, RedisConfig

    @cache()
    async def example_1(request):
        return web.Response(text="Example")

    app = web.Application()

    app.router.add_route('GET', "/", example_1)

    redis_config = RedisConfig(db=4, key_prefix="my_example")
    setup_cache(app, cache_type="redis")

    web.run_app(app, host="127.0.0.1")