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'])
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) )
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
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
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)) ]
def test_get_canonical_serializer_by_model(self): self.assertEqual( DogSerializer, DynamicRouter.get_canonical_serializer(None, model=Dog))
def test_get_canonical_serializer(self): rsrc_key = get_model_table(Dog) self.assertEqual(DogSerializer, DynamicRouter.get_canonical_serializer(rsrc_key))
def test_get_canonical_path_with_keyspace(self): rsrc_key = CatSerializer().get_resource_key() self.assertEqual('/v2/cats', DynamicRouter.get_canonical_path(rsrc_key))
def test_get_canonical_serializer(self): rsrc_key = get_model_table(Dog) self.assertEqual( DogSerializer, DynamicRouter.get_canonical_serializer(rsrc_key) )
# -*- 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),
def get_serializer_class_for_instance(self, instance): return DynamicRouter.get_canonical_serializer(resource_key=None, instance=instance)
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'}), ]
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), ]
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)) )
""" 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)),
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)) ]
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') )
def test_get_canonical_serializer_by_model(self): self.assertEqual( DogSerializer, DynamicRouter.get_canonical_serializer(None, model=Dog) )
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)), ]
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'))]
def test_get_canonical_path(self): rsrc_key = DogSerializer().get_resource_key() self.assertEqual( '/dogs', DynamicRouter.get_canonical_path(rsrc_key) )
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))]
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'))
def test_get_canonical_path(self): rsrc_key = DogSerializer().get_resource_key() self.assertEqual('/dogs', DynamicRouter.get_canonical_path(rsrc_key))
def test_get_canonical_path_with_keyspace(self): rsrc_key = CatSerializer().get_resource_key() self.assertEqual( '/v2/cats', DynamicRouter.get_canonical_path(rsrc_key) )
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()
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')), ]