Пример #1
0
    def test_unknown_resource(self):
        """Test case where polymorhpic relation pulls in an object for
        which there is no known canonical serializer.
        """

        zork = Zebra.objects.create(
            name='Zork',
            origin='San Francisco Zoo'
        )

        user = self.fixture.users[0]
        user.favorite_pet = zork
        user.save()

        self.assertIsNone(DynamicRouter.get_canonical_serializer(Zebra))

        url = '/users/%s/?include[]=favorite_pet' % user.pk
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        content = json.loads(response.content.decode('utf-8'))
        self.assertTrue('user' in content)
        self.assertFalse('zebras' in content)  # Not sideloaded
        user_obj = content['user']
        self.assertTrue('favorite_pet' in user_obj)
        self.assertEqual('Zebra', user_obj['favorite_pet']['type'])
        self.assertEqual(zork.pk, user_obj['favorite_pet']['id'])
Пример #2
0
 def test_get_canonical_serializer_by_instance(self):
     dog = Dog.objects.create(
         name='Snoopy',
         fur_color='black and white',
         origin=''
     )
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, instance=dog)
     )
Пример #3
0
    def to_internal_value(self, data):
        model_name = data.get('type', None)
        model_id = data.get('id', None)
        if model_name and model_id:
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None,
                resource_name=model_name
            )
            if serializer_class:
                model = serializer_class.get_model()
                return model.objects.get(id=model_id) if model else None

        return None
Пример #4
0
    def to_representation(self, instance):
        try:
            # Find serializer for the instance
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None,
                instance=instance
            )
            if not serializer_class:
                # Can't find canonical serializer! For now, just return
                # object name and ID, and hope the client knows what to do
                # with it.
                return self.get_pk_object(
                    instance._meta.object_name,
                    instance.pk
                )

            # We want the pk to be represented as an object with type,
            # rather than just the ID.
            pk_value = self.get_pk_object(
                serializer_class.get_name(),
                instance.pk
            )
            if self.id_only():
                return pk_value

            # Serialize the object. Note that request_fields is set, but
            # field inclusion/exclusion is disallowed via check in bind()
            r = serializer_class(
                dynamic=True,
                request_fields=self.request_fields,
                context=self.context,
                embed=self.embed
            ).to_representation(
                instance
            )

            # Pass pk object that contains type and ID to TaggedDict object
            # so that Processor can use it when the field gets sideloaded.
            if isinstance(r, TaggedDict):
                r.pk_value = pk_value
            return r
        except:
            # This feature should be considered to be in Beta so don't break
            # if anything unexpected happens.
            # TODO: Remove once we have more confidence.
            traceback.print_exc()
            return None
Пример #5
0
from django.urls import include, path

from dynamic_rest.routers import DynamicRouter

from .apiviews import UserViewSet


router = DynamicRouter()
router.register('users', UserViewSet)

urlpatterns = [
    path('', include(router.urls))
]
Пример #6
0
 def test_get_canonical_serializer_by_model(self):
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, model=Dog))
Пример #7
0
 def test_get_canonical_serializer(self):
     rsrc_key = get_model_table(Dog)
     self.assertEqual(DogSerializer,
                      DynamicRouter.get_canonical_serializer(rsrc_key))
Пример #8
0
 def test_get_canonical_path_with_keyspace(self):
     rsrc_key = CatSerializer().get_resource_key()
     self.assertEqual('/v2/cats',
                      DynamicRouter.get_canonical_path(rsrc_key))
Пример #9
0
 def test_get_canonical_serializer(self):
     rsrc_key = get_model_table(Dog)
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(rsrc_key)
     )
Пример #10
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals

import django.views.static
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http.response import HttpResponse, HttpResponseForbidden
from django.views.generic.base import RedirectView
from dynamic_rest.routers import DynamicRouter

from testapi.viewset import (AuthorizedPizzaViewSet, MenuViewSet, PizzaGroupViewSet, PizzaViewSet, ReviewViewSet,
                             ToppingViewSet, fake_oauth, fake_view, wait)

router = DynamicRouter()
router.register('pizza', PizzaViewSet, base_name='pizza')
router.register('review', ReviewViewSet)
router.register('topping', ToppingViewSet)
router.register('menulol', MenuViewSet)
router.register('pizzagroup', PizzaGroupViewSet)

router.register('authpizza', AuthorizedPizzaViewSet)

urlpatterns = [
    url(r'^api/v2/wait', wait),
    url(r'^oauth2/token/$', fake_oauth),
    url(r'^api/v2/view/$', fake_view),
    url(r'^api/v2/', include(router.urls)),
    url(r'^api/forbidden', lambda request: HttpResponseForbidden()),
    url(r'^other/view/', lambda request: HttpResponse(b'{"result": "ok"}')),
    url(r'admin/', admin.site.urls),
Пример #11
0
 def get_serializer_class_for_instance(self, instance):
     return DynamicRouter.get_canonical_serializer(resource_key=None,
                                                   instance=instance)
Пример #12
0
Файл: urls.py Проект: ksjny/api
from logit import views

from rest_framework import routers
from dynamic_rest.routers import DynamicRouter

from django.urls import include, path

router = DynamicRouter()

router.register('users', views.UserViewSet)
router.register('diagnosis', views.DiagnosisViewSet)
router.register('medication', views.MedicationViewSet)
router.register('symptom', views.SymptomViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('classify/<int:user_id>', views.classify),
    path('users/me/',
         views.UserViewSet.as_view({'get': 'retrieve'}),
         kwargs={'pk': 'me'}),
]
Пример #13
0
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from dynamic_rest.routers import DynamicRouter
from restapi import views
router = DynamicRouter()
router.register(r'spacers', views.SpacerViewSet)
router.register(r'repeats', views.RepeatViewSet)
router.register(r'organisms', views.OrganismViewSet)
router.register(r'locuspacerrepeats', views.LSRViewSet)
router.register(r'casproteins', views.CasProteinViewSet)
router.register(r'organismcas', views.OCViewSet)
router.register(r'loci', views.LocusViewSet)
router.register(r'organismselfspacers', views.OSSViewSet)
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^admin/', admin.site.urls),
]
Пример #14
0
from django.conf.urls import include, patterns, url

from dynamic_rest.routers import DynamicRouter
from tests import viewsets

router = DynamicRouter()
router.register_resource(viewsets.UserViewSet)
router.register_resource(viewsets.GroupViewSet)
router.register_resource(viewsets.ProfileViewSet)
router.register_resource(viewsets.LocationViewSet)

router.register(r'cats', viewsets.CatViewSet)
router.register_resource(viewsets.DogViewSet)
router.register_resource(viewsets.HorseViewSet)
router.register(r'zebras', viewsets.ZebraViewSet)  # not canonical
router.register(r'user_locations', viewsets.UserLocationViewSet)

# the above routes are duplicated to test versioned prefixes
router.register_resource(viewsets.CatViewSet, namespace='v2')  # canonical
router.register(r'v1/user_locations', viewsets.UserLocationViewSet)

urlpatterns = patterns(
    '',
    url(r'^', include(router.urls))
)
Пример #15
0
"""
from inspect import isclass

from django.contrib import admin
from django.conf import settings
from django.conf.urls import include, url
from django.views.decorators.csrf import csrf_exempt

import debug_toolbar
from dynamic_rest.routers import DynamicRouter
from graphene_django.views import GraphQLView

from drest import views

# auto-register views
router = DynamicRouter()

for name in dir(views):
    view = getattr(views, name)
    if isclass(view) and getattr(view, 'serializer_class', None):
        router.register_resource(view, namespace='api')

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^admin/', admin.site.urls),
    url(r'^graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))),
]

if settings.DEBUG:
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
Пример #16
0
from web import views

from rest_framework import routers
from dynamic_rest.routers import DynamicRouter

from django.conf.urls import url, include

router = DynamicRouter()
router.register('users', views.UserViewSet)
router.register('teams', views.TeamViewSet)
router.register('organizations', views.OrganizationViewSet)
router.register('memberships', views.MembershipViewSet)

router.register('reliefmaps', views.ReliefMapViewSet)

router.register(r'mapitemtemplates', views.MapItemTemplateViewSet)
router.register(r'filterpresets', views.FilterPresetViewSet)
router.register(r'templatepresets', views.TemplatePresetViewSet)
router.register(r'datalayers', views.DataLayerViewSet)

router.register(r'mapitems', views.MapItemViewSet)

urlpatterns = [
    url(r'users/me/$',
        views.UserViewSet.as_view({'get': 'retrieve'}),
        kwargs={'pk': 'me'}),
    url(r'^', include(router.urls))
]
Пример #17
0
 def test_get_canonical_path_with_pk(self):
     rsrc_key = DogSerializer().get_resource_key()
     self.assertEqual(
         '/dogs/1/',
         DynamicRouter.get_canonical_path(rsrc_key, pk='1')
     )
Пример #18
0
 def test_get_canonical_serializer_by_model(self):
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, model=Dog)
     )
Пример #19
0
from django.conf.urls import url, include
from dynamic_rest.routers import DynamicRouter

from sw import views

router = DynamicRouter()
router.register('planet', views.PlanetViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]
Пример #20
0
from django.conf.urls import include, url

from dynamic_rest.routers import DynamicRouter
from dapp1 import views
from django.contrib import admin


router = DynamicRouter()
#router.register_resource(views.UserViewSet)
#router.register_resource(views.GroupViewSet)
#router.register_resource(views.LocationViewSet)

router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'location', views.LocationViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url('admin/', admin.site.urls)
]

urlpatterns += [url(r'^silk/', include('silk.urls', namespace='silk'))]

Пример #21
0
 def test_get_canonical_path(self):
     rsrc_key = DogSerializer().get_resource_key()
     self.assertEqual(
         '/dogs',
         DynamicRouter.get_canonical_path(rsrc_key)
     )
Пример #22
0
from django.urls import include, path

from dynamic_rest.routers import DynamicRouter
from tests import viewsets

router = DynamicRouter()
router.register_resource(viewsets.UserViewSet)
router.register_resource(viewsets.GroupViewSet)
router.register_resource(viewsets.ProfileViewSet)
router.register_resource(viewsets.LocationViewSet)

router.register(r'cars', viewsets.CarViewSet)
router.register(r'cats', viewsets.CatViewSet)
router.register_resource(viewsets.DogViewSet)
router.register_resource(viewsets.HorseViewSet)
router.register_resource(viewsets.PermissionViewSet)
router.register(r'zebras', viewsets.ZebraViewSet)  # not canonical
router.register(r'user_locations', viewsets.UserLocationViewSet)
router.register(r'alternate_locations', viewsets.AlternateLocationViewSet)

# the above routes are duplicated to test versioned prefixes
router.register_resource(viewsets.CatViewSet, namespace='v2')  # canonical
router.register(r'v1/user_locations', viewsets.UserLocationViewSet)

urlpatterns = [path('', include(router.urls))]
Пример #23
0
 def test_get_canonical_path_with_pk(self):
     rsrc_key = DogSerializer().get_resource_key()
     self.assertEqual('/dogs/1/',
                      DynamicRouter.get_canonical_path(rsrc_key, pk='1'))
Пример #24
0
 def test_get_canonical_path(self):
     rsrc_key = DogSerializer().get_resource_key()
     self.assertEqual('/dogs', DynamicRouter.get_canonical_path(rsrc_key))
Пример #25
0
 def test_get_canonical_path_with_keyspace(self):
     rsrc_key = CatSerializer().get_resource_key()
     self.assertEqual(
         '/v2/cats',
         DynamicRouter.get_canonical_path(rsrc_key)
     )
Пример #26
0
 def test_get_canonical_path_with_prefix(self):
     set_script_prefix('/v2/')
     rsrc_key = DogSerializer().get_resource_key()
     self.assertEqual('/v2/dogs',
                      DynamicRouter.get_canonical_path(rsrc_key))
     clear_script_prefix()
Пример #27
0
from django.http import HttpResponse
from django.urls import path
from dynamic_rest.routers import DynamicRouter

from core.views import ItemViewSet

router = DynamicRouter()
router.register(r'items', ItemViewSet, base_name='items')
urlpatterns = router.urls

urlpatterns += [
    path('favicon.ico', lambda request: HttpResponse('empty')),
]