from ninja import Router, ModelSchema, Schema from ninja.errors import HttpError from config import models from typing import List from guardian.shortcuts import get_objects_for_user, assign_perm from django.shortcuts import get_object_or_404 router = Router() class LocalRecordingStorage(ModelSchema): class Meta: model = models.LocalRecordingStorage fields = "__all__" class LocalRecordingStoragePatch(ModelSchema): class Meta: model = models.LocalRecordingStorage exclude = ["id"] fields_optional = "__all__" extra = "forbid" @router.get('/local', response=List[LocalRecordingStorage]) def list_local_recording_storage(request): return get_objects_for_user(request.user, 'view_localrecordingstorage', models.LocalRecordingStorage.objects.all()) @router.get('/local/{id}', response=LocalRecordingStorage) def get_local_recording_storage(request, id: int): obj = get_object_or_404(models.LocalRecordingStorage, id=id) if not request.user.has_perm('view_localrecordingstorage', obj): raise HttpError(401, "unauthorized") return obj @router.post('/local', response=LocalRecordingStorage) def create_local_recording_storage(request, payload: LocalRecordingStorage): obj = models.LocalRecordingStorage.objects.create(**payload.dict()) assign_perm( 'view_localrecordingstorage', request.user, obj) assign_perm('change_localrecordingstorage', request.user, obj) assign_perm('delete_localrecordingstorage', request.user, obj) return obj @router.patch('/local/{id}', response=LocalRecordingStorage) def patch_local_recording_storage(request, id: int, payload: LocalRecordingStoragePatch): obj = get_object_or_404(models.LocalRecordingStorage, id=id) if not request.user.has_perm('change_localrecordingstorage', obj): raise HttpError(401, "unauthorized") for key, value in payload.dict(exclude_unset=True).items(): setattr(obj, key, value) obj.save() return obj @router.delete('/local/{id}', response=None) def delete_local_recording_storage(request, id: int): obj = get_object_or_404(models.LocalRecordingStorage, id=id) if not request.user.has_perm('delete_localrecordingstorage', obj): raise HttpError(401, "unauthorized") obj.delete()