1
0
Fork 0
bthlabs-jsonrpc/packages/bthlabs-jsonrpc-django/example/bthlabs_jsonrpc_django_example/things/rpc_methods.py

90 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
# django-jsonrpc-django | (c) 2022-present Tomek Wójcik | MIT License
from bthlabs_jsonrpc_core import JSONRPCAccessDeniedError, register_method
from bthlabs_jsonrpc_django_example.things.models import Thing
@register_method('things.list')
def list_things(request):
return Thing.objects.filter(
is_active=True,
owner__isnull=True,
)
@register_method('things.list', namespace='private')
def private_list_things(request):
return Thing.objects.filter(
is_active=True,
owner=request.user,
)
@register_method('things.create', namespace='private')
def private_create_thing(request, name, content):
return Thing.objects.create(
name=name,
content=content,
is_active=True,
owner=request.user,
)
@register_method('things.update', namespace='private')
def private_update_thing(request, thing_id, name=None, content=None):
thing = Thing.objects.get(pk=thing_id, is_active=True)
if thing.owner != request.user:
raise JSONRPCAccessDeniedError("You can't access this thing.")
if name is not None:
thing.name = name
if content is not None:
thing.content = content
thing.save()
return thing
@register_method('things.list', namespace='admin')
def admin_list_things(request):
return Thing.objects.all()
@register_method('things.create', namespace='admin')
def admin_create_thing(request, name, content, is_active, owner_id):
return Thing.objects.create(
name=name,
content=content,
is_active=is_active,
owner_id=owner_id,
)
@register_method('things.update', namespace='admin')
def admin_update_thing(request,
thing_id,
name=None,
content=None,
is_active=None,
owner_id=None):
thing = Thing.objects.get(pk=thing_id)
if name is not None:
thing.name = name
if content is not None:
thing.content = content
if is_active is not None:
thing.is_active = is_active
if owner_id is not None:
thing.owner_id = owner_id
thing.save()
return thing