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):
            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 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 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)
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)
    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'),
        ]
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
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)
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
Esempio n. 18
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
Esempio n. 19
0
def create_urls(datastore_loader):
    datastore = datastore_loader(settings)

    def url(pat, target, **kwargs):
        return django_url(pat, target, {'data': datastore}, **kwargs)

    apps = SimpleRouter()
    apps.register(r'app', AppViewSet, base_name='app')

    v1_urls = patterns(
        '',
        url(r'^apps/', include(apps.urls)),
    )
    v2_urls = patterns(
        '',
        ) + v1_urls

    return patterns(
        '',
        url('^api/', include(v1_urls, namespace='compat')),
        url(r'^api/v2/', include(v2_urls, namespace='api-v2')),
        url(r'^api/v1/', include(v1_urls))
    )
    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]
Esempio n. 21
0
from django.conf.urls import include, patterns, url

from rest_framework.routers import SimpleRouter

import mkt.feed.views as views
from mkt.api.base import SubRouterWithFormat
from mkt.api.v1.urls import urlpatterns as v1_urls
from mkt.api.views import endpoint_removed
from mkt.search.views import RocketbarViewV2


feed = SimpleRouter()
feed.register(r'apps', views.FeedAppViewSet, base_name='feedapps')
feed.register(r'brands', views.FeedBrandViewSet, base_name='feedbrands')
feed.register(r'collections', views.FeedCollectionViewSet,
              base_name='feedcollections')
feed.register(r'shelves', views.FeedShelfViewSet, base_name='feedshelves')
feed.register(r'items', views.FeedItemViewSet, base_name='feeditems')

subfeedapp = SubRouterWithFormat()
subfeedapp.register('image', views.FeedAppImageViewSet,
                    base_name='feed-app-image')

subfeedcollection = SubRouterWithFormat()
subfeedcollection.register('image', views.FeedCollectionImageViewSet,
                    base_name='feed-collection-image')

subfeedshelf = SubRouterWithFormat()
subfeedshelf.register('image', views.FeedShelfImageViewSet,
                      base_name='feed-shelf-image')
Esempio n. 22
0
from rest_framework.routers import SimpleRouter
from api.banners import views


router = SimpleRouter()
router.register(r'site_banners', views.SiteBannerViewSet, base_name='site_banners')
urlpatterns = router.urls
Esempio n. 23
0
from django.conf.urls import url
from rest_framework.routers import SimpleRouter
from .views import *

urlpatterns=[
	url(r'^$',IndexPage.as_view(),name='approot'),

]

router = SimpleRouter(trailing_slash=False)
router.register(r'control',Controller,'control')
urlpatterns+=router.urls
Esempio n. 24
0
from rest_framework.routers import SimpleRouter
from api.sourceregistrations import views


router = SimpleRouter()
router.register(r'sourceregistrations', views.ProviderRegistrationViewSet, base_name='sourceregistration')
urlpatterns = router.urls
Esempio n. 25
0
"""__author__ = 叶小永"""
from rest_framework.routers import SimpleRouter

from user.views import UserView

# 获取路由对象
router = SimpleRouter()
# 注册资源,/api/user/auth/  /api/user/auth/[id]/
router.register('auth', UserView)

urlpatterns = []

# 添加路由地址到urlpatterns
urlpatterns += router.urls
Esempio n. 26
0
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.renderers import JSONOpenAPIRenderer
from rest_framework.routers import SimpleRouter
from rest_framework.schemas import get_schema_view

from jogging_tracker import __version__

from . import views

router = SimpleRouter(trailing_slash=False)
router.register("activities", views.ActivityViewSet)
router.register("users", views.UserViewSet)
router.register("weather", views.WeatherViewSet)

urlpatterns = [
    path("", include(router.urls)),
    path("auth/login", obtain_auth_token, name="api_auth_token"),
    path("auth/logout", views.Logout.as_view()),
    path(
        "schema.yaml",
        get_schema_view(
            title="Jogging Tracker API",
            description="REST API that tracks jogging times of users",
            version=__version__,
        ),
        name="openapi-schema",
    ),
Esempio n. 27
0
from rest_framework.routers import SimpleRouter
from django.urls import path, include
from vehicles.views import location

from vehicles.viewsets import (LocationViewSet, VehicleCoordsViewSet,
                               VehicleViewSet, vehicle_detail)

router = SimpleRouter()
router.register('locations', LocationViewSet)
router.register('vehicle-locations', VehicleCoordsViewSet)
router.register('vehicles', VehicleViewSet)
# router.register('vehicle-detail', VehicleDetailViewSet)

urlpatterns = [
    # path('', get_location),
    path('coord/', location),
    path('vehicle-detail/<int:pk>', vehicle_detail),
    path('', include(router.urls)),
]
Esempio n. 28
0
from django.urls import path, include
from rest_framework.routers import SimpleRouter

from . import apis

router = SimpleRouter()
router.register("audio-file", apis.AudioFileViewSet, basename="audio-files")
router.register("text-file", apis.DocumentViewSet, basename="text-files")
router.register("words", apis.WordViewSet, basename="words")

urlpatterns = [path('api/', include(router.urls))]
Esempio n. 29
0
from rest_framework.routers import SimpleRouter

from risk_management.api_views import PNLListViewSet, PNLSheetViewSet

router = SimpleRouter()

router.register(r'risk_management/pnl',
                PNLListViewSet,
                basename='risk_management')
router.register(r'risk_management/pnl_sheet',
                PNLSheetViewSet,
                basename='risk_management')

risk_management_api_patterns = router.urls
Esempio n. 30
0
from django.urls import include, path
from rest_framework.routers import SimpleRouter
from bookmark.views import BookmarkQuestionViewSet, BookmarkUserViewSet

app_name = "bookmark"

router = SimpleRouter()

router.register("bookmark/user", BookmarkUserViewSet, basename="bookmark_user")

bookmark_question_detail = BookmarkQuestionViewSet.as_view({
    "post": "make",
    "delete": "destroy"
})

urlpatterns = [
    path("", include(router.urls)),
    path("bookmark/question/<int:pk>/", bookmark_question_detail),
]
Esempio n. 31
0
"""
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.views.decorators.csrf import csrf_exempt

from graphene_django.views import GraphQLView
from rest_framework.routers import SimpleRouter

# =============================================================================
# API URLs

from scribbli.universe.apiviews import (
    LocationViewSet, )

router = SimpleRouter()
router.register('location', LocationViewSet, basename='location')

# =============================================================================
# Application URLs

urlpatterns = [
    path('__graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))),
    path('api/', include(router.urls)),
    path('admin/', admin.site.urls),
    path('profiles/', include('scribbli.profiles.urls')),
    path('characters/', include('scribbli.characters.urls')),
    path('stories/', include('scribbli.stories.urls')),
    path('', include('scribbli.universe.urls')),
]
Esempio n. 32
0
from rest_framework.routers import SimpleRouter

from .views import CustomerViewSet

router = SimpleRouter()
router.register(r'customers', CustomerViewSet)
Esempio n. 33
0
from users.api import TunnistamoAuthorizationView, UserConsentViewSet, UserLoginEntryViewSet
from users.views import (LoginView, LogoutView, TunnistamoOidcAuthorizeView,
                         TunnistamoOidcEndSessionView, TunnistamoOidcTokenView,
                         RememberMeView, show_profile)

from .api import GetJWTView, UserView


class AllEnglishSchemaGenerator(SchemaGenerator):
    def get_schema(self, *args, **kwargs):
        with translation.override('en'):
            return super().get_schema(*args, **kwargs)


router = SimpleRouter()
router.register('user_identity', UserIdentityViewSet)
router.register('user_device', UserDeviceViewSet)
router.register('user_login_entry', UserLoginEntryViewSet)
router.register('service', ServiceViewSet)
router.register('user_consent', UserConsentViewSet)

v1_scope_path = path('scope/', ScopeListView.as_view(), name='scope-list')
v1_api_path = path('v1/', include((router.urls + [v1_scope_path], 'v1')))

urlpatterns = [
    path('admin/', admin.site.urls),
    path('admin/report/', staff_member_required(ReportView.as_view())),
    path('api-tokens/', get_api_tokens_view),
    path('profile/', show_profile),
    path('set-remember-me/', RememberMeView.as_view(), name='set_remember_me'),
    path('accounts/login/', LoginView.as_view(), name='login'),
Esempio n. 34
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.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import SimpleRouter

from Books import settings
from store.views import BookViewSet, auth, UserBookRelationView

router = SimpleRouter()

router.register(r'books', BookViewSet)
router.register(r'books_relation', UserBookRelationView)

urlpatterns = [
    path('admin/', admin.site.urls),
    url('', include('social_django.urls', namespace='social')),
    path('auth/', auth)
]

urlpatterns += router.urls

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns
class RegexUrlPathViewSet(viewsets.ViewSet):
    @action(detail=False, url_path='list/(?P<kwarg>[0-9]{4})')
    def regex_url_path_list(self, request, *args, **kwargs):
        kwarg = self.kwargs.get('kwarg', '')
        return Response({'kwarg': kwarg})

    @action(detail=True, url_path='detail/(?P<kwarg>[0-9]{4})')
    def regex_url_path_detail(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', '')
        kwarg = self.kwargs.get('kwarg', '')
        return Response({'pk': pk, 'kwarg': kwarg})


notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)

kwarged_notes_router = SimpleRouter()
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)

namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, basename='example')

empty_prefix_router = SimpleRouter()
empty_prefix_router.register(r'', EmptyPrefixViewSet, basename='empty_prefix')

regex_url_path_router = SimpleRouter()
regex_url_path_router.register(r'', RegexUrlPathViewSet, basename='regex')


class BasicViewSet(viewsets.ViewSet):
Esempio n. 36
0
from rest_framework.routers import SimpleRouter
from appone.views import *
router = SimpleRouter()
router.register('api/v1', StudentOps)
router.register('api/v2', UserProfiOps)

urlpatterns = router.urls
Esempio n. 37
0
from django.urls import path
from rest_framework.routers import SimpleRouter
from posts import views

router = SimpleRouter()

router.register('users', views.UserViewSet, basename='users')
router.register('', views.PostViewSet, basename='posts')

urlpatterns = router.urls

# urlpatterns = [
#     path('<int:pk>/', views.postDetail.as_view()),
#     path('', views.PostList.as_view()),
#     path('users/', views.UserList.as_view()),
#     path('users/<int:pk>', views.UserDetail.as_view())
# ]
Esempio n. 38
0
"""Urls of customers data."""
from .views import CreateCustomer, CustomersView, CustomerCreate, CustomerUpdate, CustomerDelete
from rest_framework.routers import SimpleRouter
from django.urls import path

urlpatterns = [
    path('customers', CustomersView.as_view(), name='customers'),
    path('customer/add/', CustomerCreate.as_view(), name='customer-add'),
    path('customer/<int:pk>/',
         CustomerUpdate.as_view(),
         name='customer-update'),
    path('customer/<int:pk>/delete',
         CustomerDelete.as_view(),
         name='customer-delete'),
]

router = SimpleRouter(trailing_slash=False)
router.register(r'create_customer', CreateCustomer, "CreateCustomer")

urlpatterns += router.urls
Esempio n. 39
0
from rest_framework.routers import SimpleRouter

from .views import ProjectView, CategorieView, FileView
from .models import File

app_name = 'projects'

router = SimpleRouter()
router.register('projects', ProjectView)
router.register('projects-categories', CategorieView)
router.register('files', FileView, basename=File)
Esempio n. 40
0
from django.conf.urls import include, patterns, url

from rest_framework.routers import SimpleRouter

from mkt.abuse.views import (AppAbuseViewSet, ExtensionAbuseViewSet,
                             UserAbuseViewSet, WebsiteAbuseViewSet)

abuse = SimpleRouter()
abuse.register('user', UserAbuseViewSet, base_name='user-abuse')
abuse.register('app', AppAbuseViewSet, base_name='app-abuse')
abuse.register('website', WebsiteAbuseViewSet, base_name='website-abuse')
abuse.register('extension', ExtensionAbuseViewSet, base_name='extension-abuse')

api_patterns = patterns(
    '',
    url('^abuse/', include(abuse.urls)),
)
Esempio n. 41
0
from rest_framework.routers import SimpleRouter
from api.normalizeddata import views


router = SimpleRouter()
router.register(r'normalizeddata', views.NormalizedDataViewSet, base_name='normalizeddata')
urlpatterns = router.urls
Esempio n. 42
0
# author    python
# time      18-10-23 下午12:10
# project   drtStudy
from rest_framework.routers import SimpleRouter

from book13 import views

urlpatterns = []

router = SimpleRouter()
router.register('book13', views.BookInfoViewSet, base_name="Book13")
urlpatterns += router.urls
Esempio n. 43
0
from rest_framework.routers import SimpleRouter
from . import views

# Register all API Viewsets:
api = SimpleRouter()
api.register(r'elections', views.ElectionDayView)
urlpatterns = api.urls
Esempio n. 44
0
"""
Discussion API URLs
"""
from django.conf import settings
from django.conf.urls import include, patterns, url

from rest_framework.routers import SimpleRouter

from discussion_api.views import CommentViewSet, CourseTopicsView, CourseView, ThreadViewSet

ROUTER = SimpleRouter()
ROUTER.register("threads", ThreadViewSet, base_name="thread")
ROUTER.register("comments", CommentViewSet, base_name="comment")

urlpatterns = patterns(
    "discussion_api",
    url(r"^v1/courses/{}".format(settings.COURSE_ID_PATTERN),
        CourseView.as_view(),
        name="discussion_course"),
    url(r"^v1/course_topics/{}".format(settings.COURSE_ID_PATTERN),
        CourseTopicsView.as_view(),
        name="course_topics"),
    url("^v1/", include(ROUTER.urls)),
)
Esempio n. 45
0
from django.conf.urls import url
from rest_framework.routers import SimpleRouter

from shopping.views import CompareFridgeListView
from shopping.views import ShoppingListViewSet


router = SimpleRouter()

urlpatterns = [
    url(r'shopping/(?P<pk>\d+)/comparefridge/?', CompareFridgeListView.as_view()),
]

router.register('shopping', ShoppingListViewSet)

urlpatterns.extend(router.urls)
Esempio n. 46
0
from rest_framework.routers import SimpleRouter
from django.urls import path, include
from .views import CardViewSet

router = SimpleRouter()
router.register(r'card', CardViewSet)
urlpatterns = router.urls
Esempio n. 47
0
    url(r'^receipt/', include(receipt_patterns)),
    url(r'^%s/(?P<version_id>\d+)/mini-manifest$' % mkt.APP_SLUG,
        views.mini_manifest, name='reviewers.mini_manifest'),
    url(r'^signed/%s/(?P<version_id>\d+)$' % mkt.APP_SLUG,
        views.get_signed_packaged, name='reviewers.signed'),

    url(r'''^performance/(?P<email>[^/<>"']+)?$''', views.performance,
        name='reviewers.performance'),
    url(r'^leaderboard/$', views.leaderboard, name='reviewers.leaderboard'),

    url(r'^websites/', include(website_patterns)),
)

reviewers_router = SimpleRouter()
reviewers_router.register(r'canned-responses', views.CannedResponseViewSet)
reviewers_router.register(r'scores', views.ReviewerScoreViewSet)


api_patterns = patterns(
    '',
    url(r'reviewers/', include(reviewers_router.urls)),
    url('^reviewers/search', views.ReviewersSearchView.as_view(),
        name='reviewers-search-api'),
    url('^reviewers/websites/search', ReviewersWebsiteSearchView.as_view(),
        name='reviewers-website-search-api'),
    url(r'^reviewers/websites/(?P<pk>[^/<>"\']+)/approve/$',
        views.WebsiteApprove.as_view(), name='website-approve'),
    url(r'^reviewers/websites/(?P<pk>[^/<>"\']+)/reject/$',
        views.WebsiteReject.as_view(), name='website-reject'),
    url(r'^reviewers/app/(?P<pk>[^/<>"\']+)/approve/$',
Esempio n. 48
0
    url(r'^statistical/goods_day_views/$', statistical.GoodsView.as_view()),

    url(r'^users/$', UserView.as_view()),

    url(r'^goods/simple/$', spu.SpuSimleView.as_view()),

    url(r'^goods/(?P<pk>\d+)/specs/$', specs.SpecOpTIONView.as_view()),

    url(r'^skus/categories/$', Cate3View.as_view()),

    url(r'^skus/simple/$', SKUSIMP.as_view()),
    url(r'^permission/simple/$', GroupLIView.as_view()),



]

ro  = SimpleRouter()
ro.register('goods/specs',specs.SpecViewSet,base_name='specs')

urlpatterns += ro.urls

router = DefaultRouter()
router.register('skus/images',ImageViewSet,base_name='images')
router.register('skus', SKUGoodsView, base_name='skus')
router.register('orders', OrderSet, base_name='orders')
router.register('permission/perms', PermissionView, base_name='PermissionView')
router.register('permission/groups', GroupView, base_name='PermissionView')
urlpatterns += router.urls
        fields = ('url', 'uuid', 'text')


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


class MockViewSet(viewsets.ModelViewSet):
    queryset = None
    serializer_class = None


notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)

namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, base_name='example')

urlpatterns = [
    url(r'^non-namespaced/', include(namespaced_router.urls)),
    url(r'^namespaced/', include(namespaced_router.urls, namespace='example')),
    url(r'^example/', include(notes_router.urls)),
]


class BasicViewSet(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        return Response({'method': 'list'})
Esempio n. 50
0
from django.urls import path, include
from rest_framework.routers import DefaultRouter, SimpleRouter
from grandchallenge.retina_api import views
from django.views.decorators.cache import cache_page
from django.conf import settings

app_name = "retina_api"

annotation_router = SimpleRouter()
annotation_router.register(
    "singlepolygonannotation",
    views.SinglePolygonViewSet,
    basename="singlepolygonannotation",
)
annotation_router.register(
    "polygonannotationset",
    views.PolygonAnnotationSetViewSet,
    basename="polygonannotationset",
)
annotation_router.register(
    "etdrsgridannotation",
    views.ETDRSGridAnnotationViewSet,
    basename="etdrsgridannotation",
)
annotation_router.register(
    "imagequalityannotation",
    views.ImageQualityAnnotationViewSet,
    basename="imagequalityannotation",
)
annotation_router.register(
    "imagepathologyannotation",
Esempio n. 51
0
from rest_framework.routers import SimpleRouter
from rest_framework_nested import routers
from rest_framework.authtoken import views

from django.conf import settings
from django.conf.urls.static import static

from core.views import *
from web_client.views import *
from mobile import views as mobile
from mobile.views import *

# ------ API First level routing ------

router = SimpleRouter()
router.register(r'channel', ChannelAPIView)

# ------ API Second level routing ------

channel_router = routers.NestedSimpleRouter(router,
                                            r'channel',
                                            lookup='channel')
channel_router.register(r'records', RecordAPIView, base_name='channel-records')

record_router = routers.NestedSimpleRouter(channel_router,
                                           r'records',
                                           lookup='records')
record_router.register(r'attachments',
                       AttachmentAPIView,
                       base_name='record-attachments')
Esempio n. 52
0
from django.conf.urls import url
from rest_framework.routers import SimpleRouter

from task.views import TaskView, ProjectView, CommentView, DescriptionView

router = SimpleRouter(trailing_slash=False)
router.register('task', TaskView, base_name='task')
router.register('project', ProjectView, base_name='project')
router.register('comment', CommentView, base_name='comment')
router.register('description', DescriptionView, base_name='description')

urlpatterns = router.urls
Esempio n. 53
0
from rest_framework.routers import SimpleRouter
from .views import GameViewSet

router = SimpleRouter()
router.register(r'games', GameViewSet, basename='game')

urlpatterns = router.urls
Esempio n. 54
0
from django.conf.urls import url
from meiduo_admin.views.login_view import LoginView
from meiduo_admin.views.Home_View import *
from meiduo_admin.views.user_view import *
from meiduo_admin.views.sku_view import *
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework.routers import SimpleRouter

urlpatterns = [
    # url(r'^authorizations/$', LoginView.as_view()),
    url(r'^authorizations/$', obtain_jwt_token),
    url(r'^statistical/goods_day_views/$', GoodsVisitCountView.as_view()),
    url(r"^users/$", UserListCreateView.as_view()),
    url(r'^skus/$', SKUViewSet.as_view({'get': 'list'}))
]

router = SimpleRouter()
router.register(prefix='statistical', viewset=HomeViewSet, base_name='home')
urlpatterns += router.urls
Esempio n. 55
0
from django.urls import path
from rest_framework.routers import SimpleRouter

from . import views
from .views import ImageViewSet, ImageCreateView, ImageRankingView, ImageLikeView

app_name = 'images'

router = SimpleRouter()

router.register(r'api', ImageViewSet, basename='api')

urlpatterns = [
    path('api/ranking/', ImageRankingView.as_view()),
    path('api/create-image/', ImageCreateView.as_view()),
    path('api/like/', ImageLikeView.as_view()),

    path('create/', views.image_create, name='create'),
    path('detail/<int:id>/<slug:slug>/', views.image_detail, name='detail'),
    path('like/', views.image_like, name='like'),
    path('ranking/', views.image_ranking, name='ranking'),
    path('', views.image_list, name='list'),
]

urlpatterns += router.urls
Esempio n. 56
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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

from .views import RetrievePersonListFile, GeneratePersonList, PersonViewSet

router = SimpleRouter()
router.register(r'persons', PersonViewSet)

urlpatterns = [
    url(r'^retrieve/$', RetrievePersonListFile.as_view(), name='retrieve'),
    url(r'^generate/$', GeneratePersonList.as_view(), name='generate'),
]

urlpatterns += router.urls
Esempio n. 57
0
from rest_framework.routers import SimpleRouter
from .views import ProductViewSet

router = SimpleRouter()
router.register(r'products', ProductViewSet)
urlpatterns = router.urls
Esempio n. 58
0
from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import *

router = SimpleRouter()
router.register('branch', BranchViewSet, basename='store')
router.register('staff', StaffViewSet, basename='staff')
router.register('customer', CustomerViewSet, basename='customer')
router.register('col_type', CollateralTypeViewSet, basename='col_type')
router.register('collateral', CollateralViewSet, basename='collateral')
router.register('limit', LimitViewSet, basename='limit')

urlpatterns = router.urls
Esempio n. 59
0
import django
from django.conf.urls import url
from project.organisations import views

from rest_framework.routers import SimpleRouter
from .views import OrganisationModelViewset

organisation_router = SimpleRouter()
organisation_router.register('organisation-model-viewsets',
                             OrganisationModelViewset,
                             base_name='organisation')

organisations_urlpatterns = [
    url(r'^create/$',
        view=views.CreateOrganisationView.as_view(),
        name="create"),
    url(r'^(?P<slug>[\w-]+)/$',
        view=views.RetrieveOrganisationView.as_view(),
        name="organisation"),
    url(r'^(?P<slug>[\w-]+)/members/$',
        view=views.OrganisationMembersView.as_view(),
        name="members"),
    url(r'^(?P<slug>[\w-]+)/leave/$',
        view=views.LeaveOrganisationView.as_view(),
        name="leave")
] + organisation_router.urls

members_urlpatterns = [
    url(r'^(?P<slug>[\w-]+)/members/$',
        view=views.OrganisationMembersView.as_view(),
        name="members"),
Esempio n. 60
0
from django.contrib import admin
from django.urls import path
from rest_framework.routers import DefaultRouter, SimpleRouter

from apps.character.views import CharacterViewSet, create_rating

urlpatterns = [path(r'<int:id>/rating', create_rating)]

router = SimpleRouter()
router.register(r'', CharacterViewSet, basename="character")

urlpatterns += router.urls