OpenSlides/openslides/config/views.py

63 lines
1.9 KiB
Python
Raw Normal View History

2015-06-16 14:03:42 +02:00
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import Http404
2012-02-15 12:04:11 +01:00
2015-06-16 14:03:42 +02:00
from openslides.utils.rest_api import Response, ValidationError, ViewSet
from .api import config
from .exceptions import ConfigNotFound
class ConfigViewSet(ViewSet):
"""
API endpoint to list, retrieve and update the config.
"""
def list(self, request):
"""
Lists all config variables. Everybody can see them.
"""
# TODO: Check if we need permission check here.
data = ({'key': key, 'value': value} for key, value in config.items())
return Response(data)
def retrieve(self, request, *args, **kwargs):
"""
2015-06-11 14:21:54 +02:00
Retrieves one config variable. Everybody can see it.
"""
# TODO: Check if we need permission check here.
key = kwargs['pk']
try:
data = {'key': key, 'value': config[key]}
except ConfigNotFound:
raise Http404
return Response(data)
2015-06-11 14:21:54 +02:00
def update(self, request, *args, **kwargs):
"""
2015-06-11 14:21:54 +02:00
Updates one config variable. Only managers can do this.
2015-06-16 14:03:42 +02:00
Example: {"value": 42}
"""
2015-06-16 14:03:42 +02:00
# Check permission.
if not request.user.has_perm('config.can_manage'):
self.permission_denied(request)
2015-06-16 14:03:42 +02:00
2015-06-11 14:21:54 +02:00
# Check if pk is a valid config variable key.
2015-06-16 14:03:42 +02:00
key = kwargs['pk']
2015-06-11 14:21:54 +02:00
if key not in config:
raise Http404
2015-06-16 14:03:42 +02:00
# Validate value.
form_field = config.get_config_variables()[key].form_field
value = request.data['value']
if form_field:
try:
form_field.clean(value)
except DjangoValidationError as e:
raise ValidationError({'detail': e.messages[0]})
2015-06-11 14:21:54 +02:00
# Change value.
2015-06-16 14:03:42 +02:00
config[key] = value
2015-06-11 14:21:54 +02:00
# Return response.
2015-06-16 14:03:42 +02:00
return Response({'key': key, 'value': value})