|
| 1 | +import typing as t |
| 2 | +import warnings |
| 3 | + |
| 4 | +from flask import jsonify, request |
| 5 | +from flask.scaffold import Scaffold |
| 6 | +from flask.views import MethodView |
| 7 | +from marshmallow import RAISE, ValidationError, EXCLUDE |
| 8 | +from werkzeug.exceptions import BadRequest |
| 9 | + |
| 10 | +from doku.models import db |
| 11 | +from doku.models.schemas.common import ApiSchema |
| 12 | +from doku.signals import model_created, model_updated |
| 13 | +from doku.utils.db import get_or_404, get_pagination_page, get_ordering |
| 14 | + |
| 15 | + |
| 16 | +class BaseApiView(MethodView): |
| 17 | + model: t.Type[db.Model] |
| 18 | + schema: t.Type[ApiSchema] |
| 19 | + pk_field: str = "pk" |
| 20 | + pk_type: str = "int" |
| 21 | + |
| 22 | + def get_instance(self, pk: pk_type) -> "model": |
| 23 | + return get_or_404(db.session.query(self.model).filter_by(id=pk)) |
| 24 | + |
| 25 | + def get(self, pk: t.Optional[pk_type]): |
| 26 | + if pk is None: |
| 27 | + return self.get_all() |
| 28 | + else: |
| 29 | + instance = self.get_instance(pk) |
| 30 | + schema = self.schema(many=False, include_request=True) |
| 31 | + return jsonify(schema.dump(instance)) |
| 32 | + |
| 33 | + def get_all(self): |
| 34 | + # Get page and ordering. If no specific order and direction |
| 35 | + # has been specified, None will be returned. ``order_by`` will |
| 36 | + # not complain about None being passed, so no worries there. |
| 37 | + page = get_pagination_page() |
| 38 | + ordering, order, direction = get_ordering( |
| 39 | + self.model, default_order=None, default_dir=None |
| 40 | + ) |
| 41 | + # Create a copy of request arguments and drop all entries that |
| 42 | + # are pagination specific |
| 43 | + data = dict(request.args.copy()) |
| 44 | + data.pop("page", None) |
| 45 | + data.pop("order", None) |
| 46 | + data.pop("dir", None) |
| 47 | + schemas = self.schema(many=True, include_request=True) |
| 48 | + pagination = ( |
| 49 | + self.model.query.filter_by(**data) |
| 50 | + .order_by(ordering) |
| 51 | + .paginate(page=page, per_page=10) # noqa |
| 52 | + ) |
| 53 | + result = schemas.dump(pagination.items) |
| 54 | + response = { |
| 55 | + "meta": { |
| 56 | + "pages": [page for page in pagination.iter_pages()], |
| 57 | + "has_next": pagination.has_next, |
| 58 | + "has_prev": pagination.has_prev, |
| 59 | + "next_num": pagination.next_num, |
| 60 | + "prev_num": pagination.prev_num, |
| 61 | + "page_count": pagination.pages, |
| 62 | + "per_page": pagination.per_page, |
| 63 | + }, |
| 64 | + "result": result, |
| 65 | + } |
| 66 | + return jsonify(response) |
| 67 | + |
| 68 | + def post(self, *, commit: bool = True): |
| 69 | + data = self.all_request_data() |
| 70 | + schema = self.schema( |
| 71 | + session=db.session, |
| 72 | + partial=True, |
| 73 | + many=isinstance(data, list), |
| 74 | + include_request=True, |
| 75 | + unknown=RAISE, |
| 76 | + ) |
| 77 | + try: |
| 78 | + instance = schema.load(data) |
| 79 | + except ValidationError as e: |
| 80 | + return jsonify(e.messages), BadRequest.code |
| 81 | + db.session.add(instance) |
| 82 | + model_created.send(self.model, instance=instance) |
| 83 | + if commit: |
| 84 | + db.session.commit() |
| 85 | + result = schema.dump(instance) |
| 86 | + return jsonify(result), 200 |
| 87 | + |
| 88 | + def put(self, pk: t.Optional[pk_type], *, commit: bool = True): |
| 89 | + return self.update(pk=pk, commit=commit) |
| 90 | + |
| 91 | + def patch(self, pk: t.Optional[pk_type], *, commit: bool = True): |
| 92 | + return self.update(pk=pk, commit=commit) |
| 93 | + |
| 94 | + def delete(self, pk: pk_type, commit: bool = True): |
| 95 | + instance = self.get_instance(pk) |
| 96 | + db.session.delete(instance) |
| 97 | + if commit: |
| 98 | + db.session.commit() |
| 99 | + return jsonify({"success": True}) |
| 100 | + |
| 101 | + def update(self, *, pk: t.Optional[pk_type] = None, commit: bool = True): |
| 102 | + data = self.all_request_data() |
| 103 | + if pk is not None: |
| 104 | + instance = self.get_instance(pk) |
| 105 | + schema = self.schema( |
| 106 | + instance=instance, |
| 107 | + session=db.session, |
| 108 | + unknown=EXCLUDE, |
| 109 | + include_request=True, |
| 110 | + many=False, |
| 111 | + ) |
| 112 | + else: |
| 113 | + schema = self.schema( |
| 114 | + unknown=EXCLUDE, |
| 115 | + partial=True, |
| 116 | + session=db.session, |
| 117 | + many=isinstance(data, list), |
| 118 | + include_request=True, |
| 119 | + ) |
| 120 | + |
| 121 | + try: |
| 122 | + instance = schema.load(data) |
| 123 | + except ValidationError as e: |
| 124 | + return jsonify(e.messages), BadRequest.code |
| 125 | + |
| 126 | + # Send signals that instance will be updated |
| 127 | + if isinstance(instance, list): |
| 128 | + for _instance in instance: |
| 129 | + model_updated.send(self.model, instance=_instance) |
| 130 | + else: |
| 131 | + model_updated.send(self.model, instance=instance) |
| 132 | + |
| 133 | + if commit: |
| 134 | + db.session.commit() |
| 135 | + result = schema.dump(instance) |
| 136 | + return jsonify(result) |
| 137 | + |
| 138 | + @staticmethod |
| 139 | + def all_request_data(include_args=False) -> t.Union[dict, list]: |
| 140 | + """All Request Data |
| 141 | +
|
| 142 | + Get all request data including ``args``, ``form`` and ``json``. |
| 143 | +
|
| 144 | + :param include_args: Whether to include request ``args``. This |
| 145 | + might be handy for get requests. Disabled by default. |
| 146 | + """ |
| 147 | + base_data = request.values if include_args else request.form |
| 148 | + data = dict(base_data.copy()) |
| 149 | + if request.json is not None: |
| 150 | + if isinstance(request.json, list): |
| 151 | + return request.json |
| 152 | + data.update(request.json) |
| 153 | + return data |
| 154 | + |
| 155 | + @classmethod |
| 156 | + def register(cls, app: Scaffold, name: str, url: str): |
| 157 | + if not url.endswith("/"): |
| 158 | + warnings.warn( |
| 159 | + f"URL '{url}' does not end with a trailing slash ('/').", UserWarning |
| 160 | + ) |
| 161 | + url = f"{url}/" |
| 162 | + view = cls.as_view(name) |
| 163 | + # Get all entries |
| 164 | + app.add_url_rule(url, defaults=dict(pk=None), view_func=view, methods=["GET"]) |
| 165 | + # Create entry |
| 166 | + app.add_url_rule(url, view_func=view, methods=["POST"]) |
| 167 | + # Methods on existing entries |
| 168 | + app.add_url_rule( |
| 169 | + f"{url}<{cls.pk_type}:{cls.pk_field}>/", |
| 170 | + view_func=view, |
| 171 | + methods=["GET", "PUT", "PATCH", "DELETE"] |
| 172 | + ) |
| 173 | + # Bulk operations |
| 174 | + app.add_url_rule( |
| 175 | + url, |
| 176 | + defaults=dict(pk=None), |
| 177 | + view_func=view, |
| 178 | + methods=["PUT", "PATCH"] |
| 179 | + ) |
| 180 | + |
| 181 | + |
| 182 | +def api_view_factory( |
| 183 | + view_model: t.Type[db.Model], |
| 184 | + view_schema: t.Type[ApiSchema], |
| 185 | + view_pk_field: str = BaseApiView.pk_field, |
| 186 | + view_pk_type: str = BaseApiView.pk_type, |
| 187 | + register: bool = False, |
| 188 | + register_args: t.Optional[tuple] = None, |
| 189 | +) -> t.Type[BaseApiView]: |
| 190 | + class ApiView(BaseApiView): |
| 191 | + model: t.Type[db.Model] = view_model |
| 192 | + schema: t.Type[ApiSchema] = view_schema |
| 193 | + pk_field: str = view_pk_field |
| 194 | + pk_type: str = view_pk_type |
| 195 | + |
| 196 | + if register: |
| 197 | + if not register_args: |
| 198 | + raise ValueError("'register_args' is required for registering the API view") |
| 199 | + ApiView.register(*register_args) |
| 200 | + |
| 201 | + return ApiView |
0 commit comments