class TestActionKeywordArgs(TestCase):
    """
    Ensure keyword arguments passed in the `@action` decorator
    are properly handled.  Refs #940.
    """

    def setUp(self):
        class TestViewSet(viewsets.ModelViewSet):
            permission_classes = []

            @detail_route(methods=['post'], permission_classes=[permissions.AllowAny])
            def custom(self, request, *args, **kwargs):
                return Response({
                    'permission_classes': self.permission_classes
                })

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, base_name='test')
        self.view = self.router.urls[-1].callback

    def test_action_kwargs(self):
        request = factory.post('/test/0/custom/')
        response = self.view(request)
        self.assertEqual(
            response.data,
            {'permission_classes': [permissions.AllowAny]}
        )
class TestCustomLookupFields(TestCase):
    """
    Ensure that custom lookup fields are correctly routed.
    """
    urls = 'tests.test_routers'

    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            url = serializers.HyperlinkedIdentityField(view_name='routertestmodel-detail', lookup_field='uuid')

            class Meta:
                model = RouterTestModel
                fields = ('url', 'uuid', 'text')

        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            serializer_class = NoteSerializer
            lookup_field = 'uuid'

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)

        from tests import test_routers
        urls = getattr(test_routers, 'urlpatterns')
        urls += patterns(
            '',
            url(r'^', include(self.router.urls)),
        )

        RouterTestModel.objects.create(uuid='123', text='foo bar')

    def test_custom_lookup_field_route(self):
        detail_route = self.router.urls[-1]
        detail_url_pattern = detail_route.regex.pattern
        self.assertIn('<uuid>', detail_url_pattern)

    def test_retrieve_lookup_field_list_view(self):
        response = self.client.get('/notes/')
        self.assertEqual(
            response.data,
            [{
                "url": "http://testserver/notes/123/",
                "uuid": "123", "text": "foo bar"
            }]
        )

    def test_retrieve_lookup_field_detail_view(self):
        response = self.client.get('/notes/123/')
        self.assertEqual(
            response.data,
            {
                "url": "http://testserver/notes/123/",
                "uuid": "123", "text": "foo bar"
            }
        )
    def test_basename_argument_no_warnings(self):
        router = SimpleRouter()

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, basename='mock')

        assert len(w) == 0
        assert router.registry == [
            ('mock', MockViewSet, 'mock'),
        ]
    def test_viewset_action_with_null_schema(self):
        class CustomViewSet(GenericViewSet):
            @action(detail=True, schema=None)
            def extra_action(self, pk, **kwargs):
                pass

        router = SimpleRouter()
        router.register(r'detail', CustomViewSet, basename='detail')

        generator = SchemaGenerator()
        view = generator.create_view(router.urls[0].callback, 'GET')
        assert view.schema is None
    def test_base_name_and_basename_assertion(self):
        router = SimpleRouter()

        msg = "Do not provide both the `basename` and `base_name` arguments."
        with warnings.catch_warnings(record=True) as w, \
                self.assertRaisesMessage(AssertionError, msg):
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, 'mock', base_name='mock')

        msg = "The `base_name` argument is pending deprecation in favor of `basename`."
        assert len(w) == 1
        assert str(w[0].message) == msg
class TestTrailingSlashIncluded(TestCase):
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_have_trailing_slash_by_default(self):
        expected = ['^notes/$', '^notes/(?P<pk>[^/.]+)/$']
        for idx in range(len(expected)):
            assert expected[idx] == self.urls[idx].regex.pattern
class TestTrailingSlashRemoved(TestCase):
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            model = RouterTestModel

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_can_have_trailing_slash_removed(self):
        expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
        for idx in range(len(expected)):
            self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
    def test_base_name_argument_deprecation(self):
        router = SimpleRouter()

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, base_name='mock')

        msg = "The `base_name` argument has been deprecated in favor of `basename`."
        assert len(w) == 1
        assert str(w[0].message) == msg
        assert router.registry == [
            ('mock', MockViewSet, 'mock'),
        ]
class TestTrailingSlashIncluded(TestCase):
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            model = RouterTestModel

        self.router = SimpleRouter()
        self.router.register(r"notes", NoteViewSet)
        self.urls = self.router.urls

    def test_urls_have_trailing_slash_by_default(self):
        expected = ["^notes/$", "^notes/(?P<pk>[^/.]+)/$"]
        for idx in range(len(expected)):
            self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
class TestTrailingSlashRemoved(TestCase):
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_can_have_trailing_slash_removed(self):
        expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
        for idx in range(len(expected)):
            assert expected[idx] == get_regex_pattern(self.urls[idx])
    def test_base_name_argument_deprecation(self):
        router = SimpleRouter()

        with pytest.warns(RemovedInDRF311Warning) as w:
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, base_name='mock')

        msg = "The `base_name` argument is pending deprecation in favor of `basename`."
        assert len(w) == 1
        assert str(w[0].message) == msg
        assert router.registry == [
            ('mock', MockViewSet, 'mock'),
        ]
    def setUp(self):
        MockPersonIndex().reindex()
        MockPetIndex().reindex()
        self.router = SimpleRouter()

        class FacetSerializer(HaystackFacetSerializer):

            class Meta:
                fields = ["firstname", "lastname", "created"]

        class ViewSet1(FacetMixin, HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer
            facet_serializer_class = FacetSerializer

        class ViewSet2(MoreLikeThisMixin, HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer

        class ViewSet3(HaystackViewSet):
            index_models = [MockPerson, MockPet]
            serializer_class = Serializer

        self.view1 = ViewSet1
        self.view2 = ViewSet2
        self.view3 = ViewSet3
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            model = RouterTestModel

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r"notes", NoteViewSet)
        self.urls = self.router.urls
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            model = RouterTestModel

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls
class TestDynamicListAndDetailRouter(TestCase):
    def setUp(self):
        self.router = SimpleRouter()

    def test_list_and_detail_route_decorators(self):
        routes = self.router.get_routes(DynamicListAndDetailViewSet)
        decorator_routes = [r for r in routes if not (r.name.endswith('-list') or r.name.endswith('-detail'))]

        MethodNamesMap = namedtuple('MethodNamesMap', 'method_name url_path')
        # Make sure all these endpoints exist and none have been clobbered
        for i, endpoint in enumerate([MethodNamesMap('list_custom_route_get', 'list_custom-route'),
                                      MethodNamesMap('list_route_get', 'list_route_get'),
                                      MethodNamesMap('list_route_post', 'list_route_post'),
                                      MethodNamesMap('detail_custom_route_get', 'detail_custom-route'),
                                      MethodNamesMap('detail_route_get', 'detail_route_get'),
                                      MethodNamesMap('detail_route_post', 'detail_route_post')
                                      ]):
            route = decorator_routes[i]
            # check url listing
            method_name = endpoint.method_name
            url_path = endpoint.url_path

            if method_name.startswith('list_'):
                self.assertEqual(route.url,
                                 '^{{prefix}}/{0}{{trailing_slash}}$'.format(url_path))
            else:
                self.assertEqual(route.url,
                                 '^{{prefix}}/{{lookup}}/{0}{{trailing_slash}}$'.format(url_path))
            # check method to function mapping
            if method_name.endswith('_post'):
                method_map = 'post'
            else:
                method_map = 'get'
            self.assertEqual(route.mapping[method_map], method_name)
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls
class HaystackViewSetTestCase(TestCase):

    fixtures = ["mockperson"]

    def setUp(self):
        MockPersonIndex().reindex()
        self.router = SimpleRouter()

        class ViewSet(HaystackViewSet):
            serializer_class = Serializer

        self.view = ViewSet

    def tearDown(self):
        MockPersonIndex().clear()

    def test_viewset_get_queryset_no_queryset(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_queryset(self):
        setattr(self.view, "queryset", SearchQuerySet().all())
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_index_models(self):
        setattr(self.view, "index_models", [MockPerson])
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_object(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "retrieve"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_obj_raise_404(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "retrieve"})(request, pk=100000)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_viewset_get_object_invalid_lookup_field(self):
        request = factory.get(path="/", data="", content_type="application/json")
        self.assertRaises(
            AttributeError,
            self.view.as_view(actions={"get": "retrieve"}), request, invalid_lookup=1
        )

    def test_viewset_get_obj_override_lookup_field(self):
        setattr(self.view, "lookup_field", "custom_lookup")
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "retrieve"})(request, custom_lookup=1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_more_like_this_decorator(self):
        route = self.router.get_routes(self.view)[2:].pop()
        self.assertEqual(route.url, "^{prefix}/{lookup}/more-like-this{trailing_slash}$")
        self.assertEqual(route.mapping, {"get": "more_like_this"})
    def setUp(self):
        MockPersonIndex().reindex()
        self.router = SimpleRouter()

        class ViewSet(HaystackViewSet):
            serializer_class = Serializer

        self.view = ViewSet
class TestActionAppliedToExistingRoute(TestCase):
    """
    Ensure `@detail_route` decorator raises an except when applied
    to an existing route
    """

    def test_exception_raised_when_action_applied_to_existing_route(self):
        class TestViewSet(viewsets.ModelViewSet):
            @detail_route(methods=["post"])
            def retrieve(self, request, *args, **kwargs):
                return Response({"hello": "world"})

        self.router = SimpleRouter()
        self.router.register(r"test", TestViewSet, base_name="test")

        with self.assertRaises(ImproperlyConfigured):
            self.router.urls
class TestSimpleRouter(URLPatternsTestCase, TestCase):
    router = SimpleRouter()
    router.register('basics', BasicViewSet, base_name='basic')

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

    def setUp(self):
        self.router = SimpleRouter()

    def test_action_routes(self):
        # Get action routes (first two are list/detail)
        routes = self.router.get_routes(BasicViewSet)[2:]

        assert routes[0].url == '^{prefix}/{lookup}/action1{trailing_slash}$'
        assert routes[0].mapping == {
            'post': 'action1',
        }

        assert routes[1].url == '^{prefix}/{lookup}/action2{trailing_slash}$'
        assert routes[1].mapping == {
            'post': 'action2',
            'delete': 'action2',
        }

        assert routes[2].url == '^{prefix}/{lookup}/action3{trailing_slash}$'
        assert routes[2].mapping == {
            'post': 'action3',
            'delete': 'action3_delete',
        }

    def test_multiple_action_handlers(self):
        # Standard action
        response = self.client.post(reverse('basic-action3', args=[1]))
        assert response.data == {'post': '1'}

        # Additional handler registered with MethodMapper
        response = self.client.delete(reverse('basic-action3', args=[1]))
        assert response.data == {'delete': '1'}

    def test_register_after_accessing_urls(self):
        self.router.register(r'notes', NoteViewSet)
        assert len(self.router.urls) == 2  # list and detail
        self.router.register(r'notes_bis', NoteViewSet)
        assert len(self.router.urls) == 4
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            lookup_field = 'uuid'
            lookup_value_regex = '[0-9a-f]{32}'

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls
class TestLookupValueRegex(TestCase):
    """
    Ensure the router honors lookup_value_regex when applied
    to the viewset.
    """
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            lookup_field = 'uuid'
            lookup_value_regex = '[0-9a-f]{32}'

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_limited_by_lookup_value_regex(self):
        expected = ['^notes/$', '^notes/(?P<uuid>[0-9a-f]{32})/$']
        for idx in range(len(expected)):
            assert expected[idx] == get_regex_pattern(self.urls[idx])
class TestCustomLookupFields(TestCase):
    """
    Ensure that custom lookup fields are correctly routed.
    """

    urls = "tests.test_routers"

    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            url = serializers.HyperlinkedIdentityField(view_name="routertestmodel-detail", lookup_field="uuid")

            class Meta:
                model = RouterTestModel
                fields = ("url", "uuid", "text")

        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            serializer_class = NoteSerializer
            lookup_field = "uuid"

        self.router = SimpleRouter()
        self.router.register(r"notes", NoteViewSet)

        from tests import test_routers

        urls = getattr(test_routers, "urlpatterns")
        urls += patterns("", url(r"^", include(self.router.urls)))

        RouterTestModel.objects.create(uuid="123", text="foo bar")

    def test_custom_lookup_field_route(self):
        detail_route = self.router.urls[-1]
        detail_url_pattern = detail_route.regex.pattern
        self.assertIn("<uuid>", detail_url_pattern)

    def test_retrieve_lookup_field_list_view(self):
        response = self.client.get("/notes/")
        self.assertEqual(response.data, [{"url": "http://testserver/notes/123/", "uuid": "123", "text": "foo bar"}])

    def test_retrieve_lookup_field_detail_view(self):
        response = self.client.get("/notes/123/")
        self.assertEqual(response.data, {"url": "http://testserver/notes/123/", "uuid": "123", "text": "foo bar"})
class TestLookupValueRegex(TestCase):
    """
    Ensure the router honors lookup_value_regex when applied
    to the viewset.
    """

    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            lookup_field = "uuid"
            lookup_value_regex = "[0-9a-f]{32}"

        self.router = SimpleRouter()
        self.router.register(r"notes", NoteViewSet)
        self.urls = self.router.urls

    def test_urls_limited_by_lookup_value_regex(self):
        expected = ["^notes/$", "^notes/(?P<uuid>[0-9a-f]{32})/$"]
        for idx in range(len(expected)):
            self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
    def setUp(self):
        class TestViewSet(viewsets.ModelViewSet):
            permission_classes = []

            @detail_route(methods=["post"], permission_classes=[permissions.AllowAny])
            def custom(self, request, *args, **kwargs):
                return Response({"permission_classes": self.permission_classes})

        self.router = SimpleRouter()
        self.router.register(r"test", TestViewSet, base_name="test")
        self.view = self.router.urls[-1].callback
class TestActionAppliedToExistingRoute(TestCase):
    """
    Ensure `@action` decorator raises an except when applied
    to an existing route
    """

    def test_exception_raised_when_action_applied_to_existing_route(self):
        class TestViewSet(viewsets.ModelViewSet):

            @action(methods=['post'], detail=True)
            def retrieve(self, request, *args, **kwargs):
                return Response({
                    'hello': 'world'
                })

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, basename='test')

        with pytest.raises(ImproperlyConfigured):
            self.router.urls
Exemple #27
0
def build_router_urls():
    """
    Creates a router instance to generate API urls for Customer and Internal API
    """
    routes = []
    path = os.path.join(os.path.dirname(__file__), 'backend', 'views')
    for filename in os.listdir(path):
        if os.path.isfile(os.path.join(path, filename)) and filename.endswith('.py'):
            name = filename.replace('.py', '')
            module = imp.load_source(name, os.path.join(path, filename))
            for member in inspect.getmembers(module):
                if inspect.isclass(member[1]) \
                        and member[1].__module__ == name \
                        and 'ViewSet' in [base.__name__ for base in member[1].__bases__]:
                    routes.append({'prefix': member[1].prefix,
                                   'viewset': member[1],
                                   'base_name': member[1].base_name})
    router = SimpleRouter()
    for route in routes:
        router.register(**route)
    return router.urls
    def setUp(self):
        class TestViewSet(viewsets.ModelViewSet):
            permission_classes = []

            @action(methods=['post'], detail=True, permission_classes=[permissions.AllowAny])
            def custom(self, request, *args, **kwargs):
                return Response({
                    'permission_classes': self.permission_classes
                })

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, basename='test')
        self.view = self.router.urls[-1].callback
    def test_viewset_action_with_schema(self):
        class CustomViewSet(GenericViewSet):
            @action(detail=True, schema=AutoSchema(manual_fields=[
                coreapi.Field(
                    "my_extra_field",
                    required=True,
                    location="path",
                    schema=coreschema.String()
                ),
            ]))
            def extra_action(self, pk, **kwargs):
                pass

        router = SimpleRouter()
        router.register(r'detail', CustomViewSet, basename='detail')

        generator = SchemaGenerator()
        view = generator.create_view(router.urls[0].callback, 'GET')
        link = view.schema.get_link('/a/url/{id}/', 'GET', '')
        fields = link.fields

        assert len(fields) == 2
        assert "my_extra_field" in [f.name for f in fields]
    def test_exception_raised_when_action_applied_to_existing_route(self):
        class TestViewSet(viewsets.ModelViewSet):

            @detail_route(methods=['post'])
            def retrieve(self, request, *args, **kwargs):
                return Response({
                    'hello': 'world'
                })

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, base_name='test')

        with self.assertRaises(ImproperlyConfigured):
            self.router.urls
Exemple #31
0
from django.urls import include, path
from rest_framework.routers import SimpleRouter
from . import apis

router = SimpleRouter()
router.register('countries', apis.CountryViewSet, basename='countries')
router.register('states', apis.StateViewSet, basename='states')
router.register('cities', apis.CityViewSet, basename='cities')

urlpatterns = [
    # apis
    path('api/', include(router.urls))
]
from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter

# from kda.users.api.views import UserViewSet

if settings.DEBUG:
    router = DefaultRouter()
else:
    router = SimpleRouter()

# router.register("users", UserViewSet)

app_name = "api"
urlpatterns = router.urls
Exemple #33
0
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import SimpleRouter

from orders.views import OrderView

# API urls
router = SimpleRouter()
router.register('api/orders', OrderView)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('services.urls')),
    path('orders/', include('orders.urls')),
    path('optimizer/', include('optimizer.urls'))
]

urlpatterns += router.urls
from rest_framework.routers import SimpleRouter

from .views import TaskViewSet

router = SimpleRouter()

router.register(r"tasks", TaskViewSet, basename="task")
Exemple #35
0
from django.urls import path
from .views import SellerViewSet
from .views import ClientViewSet
from .views import ProductServiceListView
from .views import ProductServiceDetailView
from .views import SaleListView
from .views import SaleDetailView
from .views import SellerCommissionView
from .views import ClientProductsView
from .views import MostSoldView
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('seller', SellerViewSet, base_name='seller')
router.register('client', ClientViewSet, base_name='client')
urlpatterns = [
    path('product-service/',
        ProductServiceListView.as_view(),
        name='product-service'
    ),
    path('product-service/<slug:pk>/',
        ProductServiceDetailView.as_view(),
        name='product-service-detail'
    ),
    path('sale/',
        SaleListView.as_view(),
        name='sale'
    ),
    path('sale/<slug:pk>/',
        SaleDetailView.as_view(),
        name='sale-detail'
Exemple #36
0
from rest_framework.routers import SimpleRouter

from .views import IngredientViewSet

router = SimpleRouter()
router.register('', IngredientViewSet, basename='ingredients')

urlpatterns = router.urls
Exemple #37
0
from rest_framework.routers import SimpleRouter

from .views import UserViewSet, PostViewSet

router = SimpleRouter()
router.register('users', UserViewSet)
router.register('', PostViewSet)

urlpatterns = router.urls
Exemple #38
0
from django.urls import path, include

from rest_framework.routers import SimpleRouter
from mobility_5g_rest_api import views

# Create a router and register our viewsets with it.
router = SimpleRouter()
router.register(r'event', views.EventViewSet)
router.register(r'climate', views.ClimateViewSet)
router.register(r'daily-inflow', views.DailyInflowViewSet)

# The API URLs are now determined automatically by the router.
urlpatterns = [
    path('', include(router.urls)),
    path('conditions_stats/', views.conditions_stats),
    path('carbon_footprint/', views.carbon_footprint),
    path('daily_excessive_speed/', views.daily_excessive_speed),
    path('circulation_vehicles/', views.circulation_vehicles),
    path('top_speed_road_traffic_summary/',
         views.top_speed_road_traffic_summary),
    path('max_daily_inflow_summary/', views.max_daily_inflow_summary),
    path('bike_lanes_stats/', views.bike_lanes_stats),
    path('current_traffic_stats/', views.current_traffic_stats),
    path('random_events_overview/', views.random_events_overview)
]
from django.conf.urls import url
from django.urls import path
from . import views
from .views import ItemViewset
from django.views.generic import TemplateView
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('itemlist', ItemViewset)

urlpatterns = [
    # path('additem'  , views.Additem , name='additem'),
    url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
    path('mobilecat', views.MobileCat.as_view(), name='mobilecat'),
    path('laptopcat', views.LaptopCat.as_view(), name='laptopcat'),
    path('homecat', views.HomeCat.as_view(), name='homecat'),
    path('itemview', views.ListUser.as_view()),
    path('itemlistview', views.ListApiUser.as_view()),

    # ================ Single ITem Product ===================================
    path('honor8x',
         views.HomeCat.as_view(template_name='single-product/honor8x.html'),
         name='honor8x'),
]

urlpatterns += router.urls
Exemple #40
0
from django.urls import path
from rest_framework.routers import SimpleRouter

from .views import PostViewSet

router = SimpleRouter()
router.register('', PostViewSet, basename='posts')

urlpatterns = router.urls
Exemple #41
0
from elasticsearchapp import viewsets
from rest_framework.routers import SimpleRouter

app_name = 'elasticsearchapp'

router = SimpleRouter()
router.register(
    prefix=r'',
    basename='elasticsearchapp',
    viewset=viewsets.ArticleDocumentView
)
urlpatterns = router.urls
Exemple #42
0
from rest_framework.routers import SimpleRouter
from library import views

router = SimpleRouter()

router.register(r'tale', views.TaleViewSet)

urlpatterns = router.urls
Exemple #43
0
"""
@author: p.dolata
"""

from rest_framework.routers import SimpleRouter

from smartpicasso.app.project.views import ProjectsView

router = SimpleRouter(trailing_slash=False)
router.register('projects', ProjectsView, basename="projects")
urlpatterns = router.urls
Exemple #44
0
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from rest_framework import routers
from rest_framework.routers import DefaultRouter, SimpleRouter
from rest_framework.authtoken import views
from rest_framework_jwt.views import obtain_jwt_token

from manager.views import UserViewset, UserInfoViewSet
from user_operation.views import AW4ViewSet, A4ViewSet, CurReciteWords

router = SimpleRouter()
router.register('user', UserViewset, basename='user')
router.register('userinfo', UserInfoViewSet, basename='userinfo')
router.register('useraw', AW4ViewSet, basename='userw')
router.register('userlearned', A4ViewSet, basename='userlearned')
router.register('usercurlearned', CurReciteWords, basename='usercurlearned')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='index.html')),
    path('', include('backend.urls')),
    path('', include(router.urls)),
    path('login/', obtain_jwt_token),
]
Exemple #45
0
from django.urls import include, path
from rest_framework.routers import SimpleRouter
from seminar.views import SeminarViewSet

app_name = 'seminar'

router = SimpleRouter()
router.register('seminar', SeminarViewSet, basename='seminar')

urlpatterns = [
    path('', include((router.urls))),
]
from django.urls import path, include
from api.warehouse.views.product import WareHouseProductsAPIView, WareHouseManufacturedProductAPIView
from api.warehouse.views.biscuit import WareHouseBiscuitAPIView
from api.warehouse.views.staff import WareHouseStaffSalaryListAPIView, WareHouseStaffSalaryDetailAPIView
from api.warehouse.views.unfit_biscuit import *
from api.warehouse.views.income import TakeMoneyModelViewSet, IncomeAPIView, ReserveMoneyDetailAPIView
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('money', TakeMoneyModelViewSet)

urlpatterns = [
    path('products/',
         WareHouseProductsAPIView.as_view(),
         name='warehouse products'),
    path('biscuits/',
         WareHouseBiscuitAPIView.as_view(),
         name='warehouse biscuits'),
    path('manufacture/products/',
         WareHouseManufacturedProductAPIView.as_view(),
         name='warehouse manufactured products'),
    path('unfit/recyclable/biscuit/',
         WareHouseUnfitRecyclableBiscuitListAPIView.as_view(),
         name='all unfit biscuit'),
    path('unfit/unrecyclable/biscuit/',
         WareHouseUnfitUnRecyclableBiscuitListAPIView.as_view(),
         name='all unfit biscuit'),
    path('take/', include(router.urls)),
    path('income/', IncomeAPIView.as_view(), name='total income'),
    path('reserve_money/', ReserveMoneyDetailAPIView.as_view()),
    path('staff/salary/lists/',
Exemple #47
0
from django.urls import path, include

from rest_framework.routers import SimpleRouter

from .views import (AthleteViewSet, ModalityViewSet, StageViewSet,
                    ResultsViewSet)
"""
Routers
"""
router = SimpleRouter()
router.register('athletes', AthleteViewSet)
router.register('modality', ModalityViewSet)
router.register('stage', StageViewSet)
router.register('results', ResultsViewSet)

url_patterns = router.urls
from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter

from app.posts.api.views import PostViewSet

router = DefaultRouter() if settings.DEBUG else SimpleRouter()
router.register("post", PostViewSet)

app_name = "api"
urlpatterns = router.urls
Exemple #49
0
"""
REST API URLs for reading and writing to the edX Hedgehog Database.
"""
from __future__ import absolute_import, unicode_literals

from django.conf.urls import url
from rest_framework.routers import SimpleRouter

from edx_api_doc_tools import make_api_info, make_docs_urls

from .views import HedgehogInfoView, HedgehogUndocumentedView, HedgehogUndocumentedViewset, HedgehogViewSet

urlpatterns = []

ROUTER = SimpleRouter()
ROUTER.register(r'api/hedgehog/v0/hogs', HedgehogViewSet, basename='hedgehog')
ROUTER.register(r'api/hedgehog/v0/undoc-viewset',
                HedgehogUndocumentedViewset,
                basename='undoc-viewset')
urlpatterns += ROUTER.urls

urlpatterns += [
    url(r'/api/hedgehog/v0/info', HedgehogInfoView.as_view()),
    url(r'/api/hedgehog/v0/undoc-view', HedgehogUndocumentedView.as_view()),
]

urlpatterns += make_docs_urls(
    make_api_info(
        title="edX Hedgehog Service API",
        version="v0",
        email="*****@*****.**",
Exemple #50
0
from rest_framework.routers import SimpleRouter
from tastypie.api import Api

from .resources import simple
from .resources.billing import CreateBillingConfigurationResource
from .resources.login import login
from .resources.notification import EventResource, NotificationResource
from .resources.package import BangoProductResource, PackageResource
from .resources.refund import RefundResource
from .resources.sbi import SBIResource
from .resources.status import DebugViewSet, StatusViewSet

bango = Api(api_name='bango')
for lib in (CreateBillingConfigurationResource, BangoProductResource,
            PackageResource, NotificationResource, EventResource,
            RefundResource, SBIResource, simple.MakePremiumResource,
            simple.UpdateRatingResource, simple.CreateBankDetailsResource):
    bango.register(lib())

# TODO: would be nice to have these a sub objects of the
# bango package instead of being on their own.
bango_drf = SimpleRouter()
bango_drf.register('status', StatusViewSet)
bango_drf.register('debug', DebugViewSet, base_name='debug')

urlpatterns = patterns(
    '',
    url(r'^login/', login, name='bango.login'),
    url(r'^', include(bango_drf.urls)),
)
Exemple #51
0
from django.urls import path
from rest_framework.routers import SimpleRouter

from movies_app.api.viewsets import ExampleViewset, MovieViewset

# urlpatterns = [
#     # path('movie/', ExampleViewset.as_view({'get': 'list', 'post': 'create'}), name='movie-list-actions'),
#     path('movierate/', RateViewSet.as_view({'get': 'list', 'post': 'create'}), name='movierate-list-actions'),
#     path('movierate/<int:pk>/',
#          RateViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
#          name='movierate-detail-actions'),
#     path('movie/', MovieViewSet.as_view({'get': 'list', 'post': 'create'}), name='movie-list-actions'),
#     path('movie/<int:pk>/',
#          MovieViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
#          name='movie-detail-actions'),
#     path('movie-example/', ExampleViewset.as_view({'get': 'list', 'post': 'create'}), name='m-e-l-a'),
#     path('movie-example/<int:pk>/',
#          ExampleViewset.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
#          name='m-e-d-a'),
# ]

# ------------------------CHANGING TO ROUTER ---------------------------------------------
router = SimpleRouter()
router.register('movie', MovieViewset)
router.register('movierate',ExampleViewset)

urlpatterns = router.urls
Exemple #52
0
from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import NewsContentViewSet

router = SimpleRouter()
router.register('news-content', NewsContentViewSet, base_name="news_content")
urlpatterns = router.urls
Exemple #53
0
from django.urls import include, path
from rest_framework.routers import DefaultRouter,SimpleRouter

from OBVapp.api import views as kv

from OBVapp.api.views import OBVindexViewSet 



routerList_OBVapp = SimpleRouter()
routerList_OBVapp.register(r"OBVindex", kv.OBVindexViewSet, 'OBVindex')


urlpatterns = [

    #path("", include(router.urls)),


    #path("obvindex/", kv.OBVindexViewSet.as_view(), name="obv-index"  )
       
]


Exemple #54
0
        raise NotImplementedError

    @action(detail=True)
    def detail_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, name='Custom Name')
    def named_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, suffix='Custom Suffix')
    def suffixed_action(self, request, *args, **kwargs):
        raise NotImplementedError


router = SimpleRouter()
router.register(r'resources', ResourceViewSet)
urlpatterns = [
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.as_view()),
    url(r'^resource/customname$', CustomNameResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)$', ResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/$', NestedResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/(?P<other>[A-Za-z]+)$', NestedResourceInstance.as_view()),
]
urlpatterns += router.urls


@override_settings(ROOT_URLCONF='tests.test_utils')
class BreadcrumbTests(TestCase):
    """
Exemple #55
0
from django.conf.urls import include, url

from rest_framework.routers import SimpleRouter
from rest_framework_nested.routers import NestedSimpleRouter

from .views import (AddonReviewerViewSet, ReviewAddonVersionViewSet,
                    ReviewAddonVersionCompareViewSet, CannedResponseViewSet)

addons = SimpleRouter()
addons.register(r'addon', AddonReviewerViewSet, basename='reviewers-addon')

versions = NestedSimpleRouter(addons, r'addon', lookup='addon')
versions.register(r'versions',
                  ReviewAddonVersionViewSet,
                  basename='reviewers-versions')

compare = NestedSimpleRouter(versions, r'versions', lookup='version')
compare.register(r'compare_to',
                 ReviewAddonVersionCompareViewSet,
                 basename='reviewers-versions-compare')

urlpatterns = [
    url(r'', include(addons.urls)),
    url(r'', include(versions.urls)),
    url(r'', include(compare.urls)),
    url(r'^canned-responses/$',
        CannedResponseViewSet.as_view(),
        name='reviewers-canned-response-list'),
]
Exemple #56
0
# Copyright (c) 2012-2013 Benjamin Bruheim <*****@*****.**>
# This file is covered by the LGPLv3 or later, read COPYING for details.
from django.conf.urls import include
from django.conf.urls import url
from rest_framework.routers import SimpleRouter
from rest_framework.urlpatterns import format_suffix_patterns

from fkws import views

router = SimpleRouter()
router.register(r'api/asrun', views.AsRunViewSet)

urlpatterns = [
    url(r'^ws/(.*)', views.wschange_redirect_view),
    url(r'^api/$', views.api_root, name='api-root'),
    url(r'^api/obtain-token$',
        views.ObtainAuthToken.as_view(),
        name='api-token-auth'),
    url(r'^api/scheduleitems/$',
        views.ScheduleitemList.as_view(),
        name='api-scheduleitem-list'),
    url(r'^api/scheduleitems/(?P<pk>\d+)$',
        views.ScheduleitemDetail.as_view(),
        name='api-scheduleitem-detail'),
    url(r'^api/videos/$', views.VideoList.as_view(), name='api-video-list'),
    url(r'^api/videos/(?P<pk>\d+)$',
        views.VideoDetail.as_view(),
        name='api-video-detail'),
    url(r'^api/videofiles/$',
        views.VideoFileList.as_view(),
        name='api-videofile-list'),
Exemple #57
0
from django.urls import path
from rest_framework.routers import SimpleRouter

from .views import UserViewSet, WordViewSet

router = SimpleRouter()
router.register('users', UserViewSet, base_name='users')
router.register('', WordViewSet, base_name='words')

urlpatterns = router.urls
Exemple #58
0
from rest_framework.routers import SimpleRouter

from . import views

router = SimpleRouter()

task_occur_router = router.register(
    prefix='',
    viewset=views.UserViewSet,
    basename='user',
)

urlpatterns = [
    *router.urls,
]
Exemple #59
0
from django.conf.urls import patterns, url, include
from django.contrib import admin
from rest_framework.routers import SimpleRouter
from .views import TestResourceViewSet

admin.autodiscover()

router = SimpleRouter()
router.register(r'test-resources', TestResourceViewSet)

urlpatterns = patterns(
    '',
    url(r'', include(router.urls)),
)
Exemple #60
0
from django.conf.urls import include, url

from rest_framework.routers import SimpleRouter
from rest_framework_nested.routers import NestedSimpleRouter

from olympia.reviews.views import ReviewViewSet
from . import views


accounts = SimpleRouter()
accounts.register(r'account', views.AccountViewSet, base_name='account')

# Router for children of /accounts/account/{account_pk}/.
sub_accounts = NestedSimpleRouter(accounts, r'account', lookup='account')
sub_accounts.register('reviews', ReviewViewSet, base_name='account-review')


urlpatterns = [
    url(r'', include(accounts.urls)),
    url(r'', include(sub_accounts.urls)),
    url(r'^authenticate/$', views.AuthenticateView.as_view(),
        name='accounts.authenticate'),
    url(r'^login/$', views.LoginView.as_view(), name='accounts.login'),
    url(r'^login/start/$',
        views.LoginStartView.as_view(),
        name='accounts.login_start'),
    url(r'^session/$', views.SessionView.as_view(),
        name='accounts.session'),
    url(r'^profile/$', views.ProfileView.as_view(), name='accounts.profile'),
    url(r'^register/$', views.RegisterView.as_view(),
        name='accounts.register'),