bbangert / beaker

WSGI middleware for sessions and caching
https://beaker.readthedocs.org/
Other
517 stars 147 forks source link

How to add cache in a async function? #198

Open vba34520 opened 3 years ago

vba34520 commented 3 years ago

How to add cache in a async function?

import asyncio
from pathlib import Path
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options

cache_opts = {
    'cache.type': 'file',
    'cache.data_dir': Path(__file__).parent / 'cache/data',
    'cache.lock_dir': Path(__file__).parent / 'cache/lock'
}

cache = CacheManager(**parse_cache_config_options(cache_opts))

# @cache.cache('fib', type='file', expire=60*5)
async def fib(n):
    if n < 2:
        return n
    return await fib(n - 1) + await fib(n - 2)

async def main():
    result = [await fib(i) for i in range(35)]
    print(result)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

It caused RuntimeWarning: coroutine 'fib' was never awaited.

Looking for your reply! Thank you.