Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

39 righe
1.7 KiB

  1. from functools import wraps
  2. from flask import request, jsonify
  3. import time
  4. class Cache:
  5. def __init__(self):
  6. """
  7. Simple caching mechanism that will only cache data if the user is not sending any GET / POST arguments in the request.
  8. Use in combination with the RouteProvider class to be able to include in a request without extra instantiation and reduce performance cost.
  9. """
  10. self.cache = {}
  11. def __call__(self, timeout):
  12. """
  13. Can be expanded to include request payload based caching - make a caching hash which includes the request.args and request.form data.
  14. Keep in mind that it is memory taxing given a dynamic request type.
  15. Caching large payload routes with thousands of possible arguments could cause a memory overflow and crash the server.
  16. """
  17. def decorator(func):
  18. @wraps(func)
  19. def wrapper(*args, **kwargs):
  20. cache_key = f"{request.method}:{request.path}"
  21. if (cache_key in self.cache and time.time() <= self.cache[cache_key]["date_expires"]) and not (
  22. request.form.keys() or request.args.keys()
  23. ):
  24. return jsonify(self.cache[cache_key]["data"])
  25. else:
  26. data = func(*args, **kwargs)
  27. expiration_time = time.time() + timeout
  28. self.cache[cache_key] = {
  29. "date_created": time.time(),
  30. "date_expires": expiration_time,
  31. "data": data
  32. }
  33. return jsonify(data)
  34. return wrapper
  35. return decorator
  36. _cache = Cache()