6
0

base.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from flask import jsonify
  2. from flask.views import View
  3. from typing import Callable
  4. from typing import Optional
  5. class ListView(View):
  6. """
  7. View that returns a list of instances of a certain class
  8. """
  9. # pylint: disable=arguments-differ
  10. methods = ['GET']
  11. model = None
  12. def __init__(self, model_cls: Optional = None, post_process: Optional[Callable] = None):
  13. self._cls = model_cls or self.model
  14. self._post_process = post_process
  15. def dispatch_request(self, **kwargs):
  16. objects = self.get_objects(**kwargs)
  17. objects = self.post_process(objects)
  18. return jsonify(objects)
  19. def get_objects(self, **kwargs):
  20. query = self._list_query(**kwargs)
  21. return self._cls.query.filter_by(**query).all()
  22. def _list_query(self, **kwargs) -> dict:
  23. return kwargs
  24. def post_process(self, objects):
  25. if self._post_process is None or not callable(self._post_process):
  26. return objects
  27. return self._post_process(objects)