1234567891011121314151617181920212223242526272829303132333435 |
- from flask import jsonify
- from flask.views import View
- from typing import Callable
- from typing import Optional
- class ListView(View):
- """
- View that returns a list of instances of a certain class
- """
- # pylint: disable=arguments-differ
- methods = ['GET']
- model = None
- def __init__(self, model_cls: Optional = None, post_process: Optional[Callable] = None):
- self._cls = model_cls or self.model
- self._post_process = post_process
- def dispatch_request(self, **kwargs):
- objects = self.get_objects(**kwargs)
- objects = self.post_process(objects)
- return jsonify(objects)
- def get_objects(self, **kwargs):
- query = self._list_query(**kwargs)
- return self._cls.query.filter_by(**query).all()
- def _list_query(self, **kwargs) -> dict:
- return kwargs
- def post_process(self, objects):
- if self._post_process is None or not callable(self._post_process):
- return objects
- return self._post_process(objects)
|