2015-02-04 00:08:38 +01:00
|
|
|
import re
|
|
|
|
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
2015-01-17 14:01:44 +01:00
|
|
|
from django.core.urlresolvers import reverse
|
2015-03-29 15:49:37 +02:00
|
|
|
from rest_framework.decorators import detail_route # noqa
|
2015-02-12 18:48:14 +01:00
|
|
|
from rest_framework.serializers import ( # noqa
|
|
|
|
CharField,
|
2015-02-18 01:45:39 +01:00
|
|
|
Field,
|
2015-04-30 19:13:28 +02:00
|
|
|
IntegerField,
|
2015-02-12 18:48:14 +01:00
|
|
|
ListSerializer,
|
|
|
|
ModelSerializer,
|
|
|
|
PrimaryKeyRelatedField,
|
|
|
|
RelatedField,
|
2015-02-12 20:57:05 +01:00
|
|
|
SerializerMethodField,
|
|
|
|
ValidationError)
|
2015-02-12 18:48:14 +01:00
|
|
|
from rest_framework.response import Response # noqa
|
|
|
|
from rest_framework.routers import DefaultRouter
|
2015-02-18 01:45:39 +01:00
|
|
|
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet, ViewSet # noqa
|
2015-03-29 14:42:27 +02:00
|
|
|
from rest_framework.decorators import list_route # noqa
|
2014-10-11 14:15:42 +02:00
|
|
|
|
2015-02-04 00:08:38 +01:00
|
|
|
from .exceptions import OpenSlidesError
|
|
|
|
|
2015-02-12 18:48:14 +01:00
|
|
|
router = DefaultRouter()
|
2015-01-17 14:01:44 +01:00
|
|
|
|
|
|
|
|
|
|
|
class RESTModelMixin:
|
|
|
|
"""
|
|
|
|
Mixin for django models which are used in our rest api.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def get_root_rest_element(self):
|
|
|
|
"""
|
|
|
|
Returns the root rest instance.
|
|
|
|
|
|
|
|
Uses self as default.
|
|
|
|
"""
|
|
|
|
return self
|
|
|
|
|
|
|
|
def get_root_rest_url(self):
|
|
|
|
"""
|
|
|
|
Returns the detail url of the root model of this object.
|
|
|
|
"""
|
|
|
|
# Gets the default url-name in the same way as django rest framework
|
|
|
|
# does in relations.HyperlinkedModelSerializer
|
|
|
|
root_instance = self.get_root_rest_element()
|
|
|
|
rest_url = '%s-detail' % type(root_instance)._meta.object_name.lower()
|
|
|
|
return reverse(rest_url, args=[str(root_instance.pk)])
|
2015-02-04 00:08:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_collection_and_id_from_url(url):
|
|
|
|
"""
|
|
|
|
Helper function. Returns a tuple containing the collection name and the id
|
|
|
|
extracted out of the given REST api URL.
|
|
|
|
|
|
|
|
For example get_collection_and_id_from_url('http://localhost/api/users/user/3/')
|
|
|
|
returns ('users/user', '3').
|
|
|
|
|
|
|
|
Raises OpenSlidesError if the URL is invalid.
|
|
|
|
"""
|
|
|
|
path = urlparse(url).path
|
2015-01-30 11:58:36 +01:00
|
|
|
match = re.match(r'^/rest/(?P<collection>[-\w]+/[-\w]+)/(?P<id>[-\w]+)/$', path)
|
2015-02-04 00:08:38 +01:00
|
|
|
if not match:
|
|
|
|
raise OpenSlidesError('Invalid REST api URL: %s' % url)
|
2015-01-30 11:58:36 +01:00
|
|
|
return match.group('collection'), match.group('id')
|