|
| 1 | +import os |
| 2 | +import asyncio |
| 3 | +import functools |
| 4 | + |
1 | 5 | from django.http import HttpRequest, HttpResponse |
2 | 6 | from idom.config import IDOM_WED_MODULES_DIR |
| 7 | +from django.core.cache import caches |
| 8 | + |
| 9 | +from .config import IDOM_WEB_MODULE_CACHE, IDOM_WEB_MODULE_LRU_CACHE_SIZE |
| 10 | + |
| 11 | + |
| 12 | +if IDOM_WEB_MODULE_CACHE is None: |
| 13 | + |
| 14 | + def async_lru_cache(*lru_cache_args, **lru_cache_kwargs): |
| 15 | + def async_lru_cache_decorator(async_function): |
| 16 | + @functools.lru_cache(*lru_cache_args, **lru_cache_kwargs) |
| 17 | + def cached_async_function(*args, **kwargs): |
| 18 | + coroutine = async_function(*args, **kwargs) |
| 19 | + return asyncio.ensure_future(coroutine) |
| 20 | + |
| 21 | + return cached_async_function |
| 22 | + |
| 23 | + return async_lru_cache_decorator |
| 24 | + |
| 25 | + @async_lru_cache(IDOM_WEB_MODULE_LRU_CACHE_SIZE) |
| 26 | + async def web_modules_file(request: HttpRequest, file: str) -> HttpResponse: |
| 27 | + file_path = IDOM_WED_MODULES_DIR.current.joinpath(*file.split("/")) |
| 28 | + return HttpResponse(file_path.read_text(), content_type="text/javascript") |
| 29 | + |
| 30 | + |
| 31 | +else: |
| 32 | + _web_module_cache = caches[IDOM_WEB_MODULE_CACHE] |
| 33 | + |
| 34 | + async def web_modules_file(request: HttpRequest, file: str) -> HttpResponse: |
| 35 | + file = IDOM_WED_MODULES_DIR.current.joinpath(*file.split("/")).absolute() |
| 36 | + last_modified_time = os.stat(file).st_mtime |
| 37 | + cache_key = f"{file}:{last_modified_time}" |
3 | 38 |
|
| 39 | + response = _web_module_cache.get(cache_key) |
| 40 | + if response is None: |
| 41 | + response = HttpResponse(file.read_text(), content_type="text/javascript") |
| 42 | + _web_module_cache.set(cache_key, response, timeout=None) |
4 | 43 |
|
5 | | -def web_modules_file(request: HttpRequest, file: str) -> HttpResponse: |
6 | | - file_path = IDOM_WED_MODULES_DIR.current.joinpath(*file.split("/")) |
7 | | - return HttpResponse(file_path.read_text(), content_type="text/javascript") |
| 44 | + return response |
0 commit comments