コード例 #1
0
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
    ret = []
    for urlpattern in urlpatterns:
        if isinstance(urlpattern, RegexURLResolver):
            # Set of included URL patterns
            regex = urlpattern.regex.pattern
            namespace = urlpattern.namespace
            app_name = urlpattern.app_name
            kwargs = urlpattern.default_kwargs
            # Add in the included patterns, after applying the suffixes
            patterns = apply_suffix_patterns(urlpattern.url_patterns,
                                             suffix_pattern,
                                             suffix_required)
            ret.append(url(regex, include(patterns, namespace, app_name), kwargs))

        else:
            # Regular URL pattern
            regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
            view = urlpattern._callback or urlpattern._callback_str
            kwargs = urlpattern.default_args
            name = urlpattern.name
            # Add in both the existing and the new urlpattern
            if not suffix_required:
                ret.append(urlpattern)
            ret.append(url(regex, view, kwargs, name))

    return ret
コード例 #2
0
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
    ret = []
    for urlpattern in urlpatterns:
        if isinstance(urlpattern, RegexURLResolver):
            # Set of included URL patterns
            regex = urlpattern.regex.pattern
            namespace = urlpattern.namespace
            app_name = urlpattern.app_name
            kwargs = urlpattern.default_kwargs
            # Add in the included patterns, after applying the suffixes
            patterns = apply_suffix_patterns(urlpattern.url_patterns,
                                             suffix_pattern, suffix_required)
            ret.append(
                url(regex, include(patterns, namespace, app_name), kwargs))

        else:
            # Regular URL pattern
            regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
            view = urlpattern._callback or urlpattern._callback_str
            kwargs = urlpattern.default_args
            name = urlpattern.name
            # Add in both the existing and the new urlpattern
            if not suffix_required:
                ret.append(urlpattern)
            ret.append(url(regex, view, kwargs, name))

    return ret
コード例 #3
0
 def test_included_urls(self):
     nested_patterns = patterns("", url(r"^path$", dummy_view))
     urlpatterns = patterns("", url(r"^test/", include(nested_patterns), {"foo": "bar"}))
     test_paths = [
         URLTestPath("/test/path", (), {"foo": "bar"}),
         URLTestPath("/test/path.api", (), {"foo": "bar", "format": "api"}),
         URLTestPath("/test/path.asdf", (), {"foo": "bar", "format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #4
0
 def test_included_urls(self):
     nested_patterns = patterns(
         '',
         url(r'^path$', dummy_view)
     )
     urlpatterns = patterns(
         '',
         url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test/path', (), {'foo': 'bar', }),
         URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
         URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #5
0
ファイル: routers.py プロジェクト: mikhuang/drf-toolbox
    def get_urls(self):
        """Return a list of URL patterns, including a default root view
        for the API, and appending format suffixes.

        Unlike the superclass method, ensure that format suffixes also
        strip trailing slashes.
        """
        answer = []

        # Add all urlpatterns from the superclass method to the answer,
        # but modify the .format URL to expunge the trailing slash.
        for urlpattern in super(Router, self).get_urls():
            if '/\\.(?P<format>' in urlpattern.regex.pattern:
                answer.append(
                    url(
                        urlpattern.regex.pattern.replace(
                            '/\\.(?P<format>', '\\.(?P<format>'),
                        urlpattern._callback or urlpattern._callback_str,
                        urlpattern.default_args,
                        urlpattern.name,
                    ))
            else:
                answer.append(urlpattern)

        # Any urlpatterns defined by child routers should also
        # be included here.
        for prefix, child in self.children.items():
            for urlpattern in child.get_urls():
                answer.append(urlpattern)

        # Done; return the final answer.
        return answer
コード例 #6
0
ファイル: routers.py プロジェクト: Bazzinga/drf-toolbox
    def get_urls(self):
        """Return a list of URL patterns, including a default root view
        for the API, and appending format suffixes.

        Unlike the superclass method, ensure that format suffixes also
        strip trailing slashes.
        """
        answer = []

        # Add all urlpatterns from the superclass method to the answer,
        # but modify the .format URL to expunge the trailing slash.
        for urlpattern in super(Router, self).get_urls():
            if '/\\.(?P<format>' in urlpattern.regex.pattern:
                answer.append(url(
                    urlpattern.regex.pattern.replace('/\\.(?P<format>',
                                                     '\\.(?P<format>'),
                    urlpattern._callback or urlpattern._callback_str,
                    urlpattern.default_args,
                    urlpattern.name,
                ))
            else:
                answer.append(urlpattern)

        # Any urlpatterns defined by child routers should also
        # be included here.
        for prefix, child in self.children.items():
            for urlpattern in child.get_urls():
                answer.append(urlpattern)

        # Done; return the final answer.
        return answer
コード例 #7
0
    def get_urls(self):
        """
        Use the registered viewsets to generate a list of URL patterns.
        """
        ret = []

        for prefix, viewset, basename in self.registry:
            lookup = self.get_lookup_regex(viewset)
            routes = self.get_routes(viewset)

            for route in routes:

                # Only actions which actually exist on the viewset will be bound
                mapping = self.get_method_map(viewset, route.mapping)
                if not mapping:
                    continue

                # Build the url pattern
                regex = route.url.format(
                    prefix=prefix,
                    lookup=lookup,
                    trailing_slash=self.trailing_slash
                )
                view = viewset.as_view(mapping, **route.initkwargs)
                name = route.name.format(basename=basename)
                ret.append(url(regex, view, name=name))

        return ret
コード例 #8
0
 def test_default_args(self):
     urlpatterns = patterns("", url(r"^test$", dummy_view, {"foo": "bar"}))
     test_paths = [
         URLTestPath("/test", (), {"foo": "bar"}),
         URLTestPath("/test.api", (), {"foo": "bar", "format": "api"}),
         URLTestPath("/test.asdf", (), {"foo": "bar", "format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #9
0
 def test_format_suffix(self):
     urlpatterns = patterns("", url(r"^test$", dummy_view))
     test_paths = [
         URLTestPath("/test", (), {}),
         URLTestPath("/test.api", (), {"format": "api"}),
         URLTestPath("/test.asdf", (), {"format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #10
0
 def test_default_args(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view, {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test', (), {'foo': 'bar', }),
         URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}),
         URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #11
0
 def test_format_suffix(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view),
     )
     test_paths = [
         URLTestPath('/test', (), {}),
         URLTestPath('/test.api', (), {'format': 'api'}),
         URLTestPath('/test.asdf', (), {'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #12
0
 def test_format_suffix(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view),
     )
     test_paths = [
         URLTestPath('/test', (), {}),
         URLTestPath('/test.api', (), {'format': 'api'}),
         URLTestPath('/test.asdf', (), {'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #13
0
 def test_included_urls(self):
     nested_patterns = patterns('', url(r'^path$', dummy_view))
     urlpatterns = patterns(
         '',
         url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test/path', (), {
             'foo': 'bar',
         }),
         URLTestPath('/test/path.api', (), {
             'foo': 'bar',
             'format': 'api'
         }),
         URLTestPath('/test/path.asdf', (), {
             'foo': 'bar',
             'format': 'asdf'
         }),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #14
0
    def get_urls(self):
        """
        Generate the list of URL patterns, including a default root view
        for the API, and appending `.json` style format suffixes.
        """
        urls = []

        if self.include_root_view:
            root_url = url(r'^$', self.get_api_root_view(), name=self.root_view_name)
            urls.append(root_url)

        default_urls = super(DefaultRouter, self).get_urls()
        urls.extend(default_urls)

        if self.include_format_suffixes:
            urls = format_suffix_patterns(urls)

        return urls
コード例 #15
0
 def test_default_args(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view, {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test', (), {
             'foo': 'bar',
         }),
         URLTestPath('/test.api', (), {
             'foo': 'bar',
             'format': 'api'
         }),
         URLTestPath('/test.asdf', (), {
             'foo': 'bar',
             'format': 'asdf'
         }),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
コード例 #16
0
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = "uuid"
                fields = ("url", "uuid", "text")

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

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

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

        from rest_framework.tests import test_routers

        urls = getattr(test_routers, "urlpatterns")
        urls += patterns("", url(r"^", include(self.router.urls)))
コード例 #17
0
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = 'uuid'
                fields = ('url', 'uuid', 'text')

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

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

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

        from rest_framework.tests import test_routers
        urls = getattr(test_routers, 'urlpatterns')
        urls += patterns('',
            url(r'^', include(self.router.urls)),
        )
コード例 #18
0
ファイル: test_routers.py プロジェクト: etnperlong/mese2014
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = 'uuid'
                fields = ('url', 'uuid', 'text')

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

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

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

        from rest_framework.tests import test_routers
        urls = getattr(test_routers, 'urlpatterns')
        urls += patterns('',
            url(r'^', include(self.router.urls)),
        )
コード例 #19
0
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
    """
    Supplement existing urlpatterns with corresponding patterns that also
    include a '.format' suffix.  Retains urlpattern ordering.

    urlpatterns:
        A list of URL patterns.

    suffix_required:
        If `True`, only suffixed URLs will be generated, and non-suffixed
        URLs will not be used.  Defaults to `False`.

    allowed:
        An optional tuple/list of allowed suffixes.  eg ['json', 'api']
        Defaults to `None`, which allows any suffix.
    """
    suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
    if allowed:
        if len(allowed) == 1:
            allowed_pattern = allowed[0]
        else:
            allowed_pattern = '(%s)' % '|'.join(allowed)
        suffix_pattern = r'\.(?P<%s>%s)$' % (suffix_kwarg, allowed_pattern)
    else:
        suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg

    ret = []
    for urlpattern in urlpatterns:
        # Form our complementing '.format' urlpattern
        regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
        view = urlpattern._callback or urlpattern._callback_str
        kwargs = urlpattern.default_args
        name = urlpattern.name
        # Add in both the existing and the new urlpattern
        if not suffix_required:
            ret.append(urlpattern)
        ret.append(url(regex, view, kwargs, name))
    return ret
コード例 #20
0
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from rest_framework.compat import patterns, url


def dummy_view(request, pk):
    pass

urlpatterns = patterns('',
    url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'),
    url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'),
    url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
    url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
    url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
)


# ManyToMany

class ManyToManyTarget(models.Model):
    name = models.CharField(max_length=100)


class ManyToManySource(models.Model):
    name = models.CharField(max_length=100)
    targets = models.ManyToManyField(ManyToManyTarget, related_name='sources')


class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
    sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail')
コード例 #21
0
@api_view(('GET', ))
@renderer_classes((TemplateHTMLRenderer, ))
def permission_denied(request):
    raise PermissionDenied()


@api_view(('GET', ))
@renderer_classes((TemplateHTMLRenderer, ))
def not_found(request):
    raise Http404()


urlpatterns = patterns(
    '',
    url(r'^$', example),
    url(r'^permission_denied$', permission_denied),
    url(r'^not_found$', not_found),
)


class TemplateHTMLRendererTests(TestCase):
    urls = 'rest_framework.tests.htmlrenderer'

    def setUp(self):
        """
        Monkeypatch get_template
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name):
コード例 #22
0
    renderer_classes = (BrowsableAPIRenderer, )

    def get(self, request, **kwargs):
        return Response('text')


class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        return Response('text')


urlpatterns = patterns(
    '',
    url(r'^.*\.(?P<format>.+)$',
        MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^cache$', MockGETView.as_view()),
    url(r'^jsonp/jsonrenderer$',
        MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
    url(r'^jsonp/nojsonrenderer$',
        MockGETView.as_view(renderer_classes=[JSONPRenderer])),
    url(r'^html$', HTMLView.as_view()), url(r'^html1$', HTMLView1.as_view()),
    url(r'^api', include('rest_framework.urls', namespace='rest_framework')))


class POSTDeniedPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method != 'POST'

コード例 #23
0
        class Meta:
            model = BasicModel
            fields = ['text']

    class IncorrectlyConfiguredRootView(generics.ListCreateAPIView):
        model = FilterableItem
        filter_class = MisconfiguredFilter
        filter_backend = filters.DjangoFilterBackend

    class FilterClassDetailView(generics.RetrieveAPIView):
        model = FilterableItem
        filter_class = SeveralFieldsFilter
        filter_backend = filters.DjangoFilterBackend

    urlpatterns = patterns('',
        url(r'^(?P<pk>\d+)/$', FilterClassDetailView.as_view(), name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date}

    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
        for i in range(10):
            text = chr(i + ord(base_data[0])) * 3  # Produces string 'aaa', 'bbb', etc.
コード例 #24
0
from django.core.urlresolvers import reverse

from rest_framework.compat import patterns, url
from rest_framework.test import APITestCase
from rest_framework.tests.models import NullableForeignKeySource
from rest_framework.tests.serializers import NullableFKSourceSerializer
from rest_framework.tests.views import NullableFKSourceDetail


urlpatterns = patterns(
    '',
    url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'),
)


class NullableForeignKeyTests(APITestCase):
    """
    DRF should be able to handle nullable foreign keys when a test
    Client POST/PUT request is made with its own serialized object.
    """
    urls = 'rest_framework.tests.test_nullable_fields'

    def test_updating_object_with_null_fk(self):
        obj = NullableForeignKeySource(name='example', target=None)
        obj.save()
        serialized_data = NullableFKSourceSerializer(obj).data

        response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data)

        self.assertEqual(response.data, serialized_data)
コード例 #25
0
class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
    model = OptionalRelationModel
    model_serializer_class = serializers.HyperlinkedModelSerializer


class ExtraKwargDetailSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ExtraKwargModel

class ExtraKwargDetail(generics.RetrieveUpdateDestroyAPIView):
    model = ExtraKwargModel
    serializer_class = ExtraKwargDetailSerializer

urlpatterns = patterns('',
    url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
    url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'),
    url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'),
    url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'),
    url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'),
    url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
    url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
    url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'),
    url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
    url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
    url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
    url(r'^root/(?P<extra_kwarg>\d+)/extrakwarg/(?P<pk>\d+)/$', ExtraKwargDetail.as_view(), name='extrakwargmodel-detail'),
)


class TestBasicHyperlinkedView(TestCase):
コード例 #26
0
                                         NullableForeignKeySource,
                                         OneToOneTarget,
                                         NullableOneToOneSource)

factory = RequestFactory()
request = factory.get(
    '/')  # Just to ensure we have a request in the serializer context


def dummy_view(request, pk):
    pass


urlpatterns = patterns(
    '',
    url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'),
    url(r'^manytomanysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='manytomanysource-detail'),
    url(r'^manytomanytarget/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='manytomanytarget-detail'),
    url(r'^foreignkeysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='foreignkeysource-detail'),
    url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='foreignkeytarget-detail'),
    url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='nullableforeignkeysource-detail'),
# we are over writing tests as they hit a bug that's been fixed but not pushed 
# at the time of writing
# https://github.com/tomchristie/django-rest-framework/issues/960
from hyperlinked_relational_serializer import serializers_copy as serializers
# from rest_framework import serializers

factory = RequestFactory()
request = factory.get('/') 


def fake_view(request):
    pass


urlpatterns = patterns('',
    url(r'^vegetable/$', fake_view, name = 'vegetable-list'),
    url(r'^vegetable/(?P<pk>[0-9]+)/$', fake_view, name = 'vegetable-detail'),
    url(r'^meat/$', fake_view, name = 'meat-list'),
    url(r'^meat/(?P<pk>[0-9]+)/$', fake_view, name = 'meat-detail'),
    url(r'^meal/$', fake_view, name = 'meal-list'),
    url(r'^meal/(?P<pk>[0-9]+)/$', fake_view, name = 'meal-detail'),
)


class VegetableSerializer(HyperLinkedRelationalSerializer):

    class Meta:
        view_name = "vegetable-detail"
        queryset = Vegetable.objects.all()
        model = Vegetable
コード例 #28
0
class HTMLView(APIView):
    renderer_classes = (BrowsableAPIRenderer, )

    def get(self, request, **kwargs):
        return Response('text')


class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        return Response('text')


urlpatterns = patterns('',
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^restframework', include('rest_framework.urls', namespace='rest_framework'))
)


# TODO: Clean tests bellow - remove duplicates with above, better unit testing, ...
class RendererIntegrationTests(TestCase):
    """
    End-to-end testing of renderers using an ResponseMixin on a generic view.
    """

    urls = 'rest_framework.tests.response'
コード例 #29
0
# -*- coding: utf-8 -*-
from rest_framework.compat import patterns, url

from .views import client_headers_bounce

urlpatterns = patterns(
    'django.contrib.auth.views',
    url(r'^client_headers_bounce/', client_headers_bounce),
)
コード例 #30
0
from rest_framework.reverse import reverse

from generic_relations.relations import GenericRelatedField
from generic_relations.tests.models import Bookmark, Note, Tag

factory = RequestFactory()
# Just to ensure we have a request in the serializer context
request = factory.get('/')


def dummy_view(request, pk):
    pass


urlpatterns = [
    url(r'^bookmark/(?P<pk>[0-9]+)/$', dummy_view, name='bookmark-detail'),
    url(r'^note/(?P<pk>[0-9]+)/$', dummy_view, name='note-detail'),
    url(r'^tag/(?P<pk>[0-9]+)/$', dummy_view, name='tag-detail'),
    url(r'^contact/(?P<my_own_slug>[-\w]+)/$',
        dummy_view,
        name='contact-detail'),
]


class BookmarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Bookmark
        exclude = ('id', )


class NoteSerializer(serializers.ModelSerializer):
コード例 #31
0
ファイル: urls.py プロジェクト: jeanbritz/django-skripsie
"""
Login and logout views for the browsable API.

Add these to your root URLconf if you're using the browsable API and
your API requires authentication.

The urls must be namespaced as 'rest_framework', and you should make sure
your authentication settings include `SessionAuthentication`.

    urlpatterns = patterns('',
        ...
        url(r'^auth', include('rest_framework.urls', namespace='rest_framework'))
    )
"""
from __future__ import unicode_literals
from rest_framework.compat import patterns, url

template_name = {'template_name': 'rest_framework/login.html'}

urlpatterns = patterns(
    'django.contrib.auth.views',
    url(r'^login/$', 'login', template_name, name='login'),
    url(r'^logout/$', 'logout', template_name, name='logout'),
)
コード例 #32
0
ファイル: urls.py プロジェクト: light-it/traceparent
            'add':
            reverse('tp_metadata_snippet_update_assigned_marks_add',
                    args,
                    request=self.request),
            'remove':
            reverse('tp_metadata_snippet_update_assigned_marks_remove',
                    args,
                    request=self.request),
        })

        return Response(data)


urlpatterns = patterns(
    '',
    url(r'^$', MetadataView.as_view(), name='tp_metadata'),

    # Snippet
    url(r'^snippet/$', SnippetView.as_view(), name='tp_metadata_snippet'),
    url(r'^snippet/filter/$',
        SnippetFilterView.as_view(),
        name='tp_metadata_snippet_filter'),
    url(r'^snippet/create/$',
        SnippetCreateView.as_view(),
        name='tp_metadata_snippet_create'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/$',
        SnippetRetrieveView.as_view(),
        name='tp_metadata_snippet_retrieve'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/$',
        SnippetUpdateView.as_view(),
        name='tp_metadata_snippet_update'),
コード例 #33
0
    pass


class ResourceInstance(APIView):
    pass


class NestedResourceRoot(APIView):
    pass


class NestedResourceInstance(APIView):
    pass

urlpatterns = patterns('',
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.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()),
)


class BreadcrumbTests(TestCase):
    """Tests the breadcrumb functionality used by the HTML renderer."""

    urls = 'rest_framework.tests.breadcrumbs'

    def test_root_breadcrumbs(self):
        url = '/'
        self.assertEqual(get_breadcrumbs(url), [('Root', '/')])
コード例 #34
0
    A debug class analogous to the OAuth2AuthenticationDebug class that tests
    the OAuth2 flow with the access token sent in a query param."""
    allow_query_params_token = True


# The following patch overrides the URL patterns for the MockView class used in
# rest_framework.tests.test_authentication so that the corresponding AllowInactiveUser
# classes are tested instead.
@skipUnless(settings.FEATURES.get('ENABLE_OAUTH2_PROVIDER'), 'OAuth2 not enabled')
@patch.object(
    test_authentication,
    'urlpatterns',
    patterns(
        '',
        url(
            r'^oauth2-test/$',
            test_authentication.MockView.as_view(authentication_classes=[OAuth2AuthenticationAllowInactiveUser])
        ),
        url(
            r'^oauth2-test-debug/$',
            test_authentication.MockView.as_view(authentication_classes=[OAuth2AuthAllowInactiveUserDebug])
        ),
        url(
            r'^oauth2-with-scope-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser],
                permission_classes=[permissions.TokenHasReadWriteScope]
            )
        )
    )
)
class OAuth2AuthenticationAllowInactiveUserTestCase(test_authentication.OAuth2Tests):
コード例 #35
0
    the OAuth2 flow with the access token sent in a query param."""
    allow_query_params_token = True


# The following patch overrides the URL patterns for the MockView class used in
# rest_framework.tests.test_authentication so that the corresponding AllowInactiveUser
# classes are tested instead.
@skipUnless(settings.FEATURES.get('ENABLE_OAUTH2_PROVIDER'),
            'OAuth2 not enabled')
@patch.object(
    test_authentication, 'urlpatterns',
    patterns(
        '',
        url(
            r'^oauth2-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser
                                        ])),
        url(
            r'^oauth2-test-debug/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthAllowInactiveUserDebug])),
        url(
            r'^oauth2-with-scope-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser],
                permission_classes=[permissions.TokenHasReadWriteScope]))))
class OAuth2AuthenticationAllowInactiveUserTestCase(
        test_authentication.OAuth2Tests):
    """
    Tests the OAuth2AuthenticationAllowInactiveUser class by running all the existing tests in
コード例 #36
0
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import APIClient, APIRequestFactory, force_authenticate


@api_view(['GET', 'POST'])
def view(request):
    return Response({
        'auth': request.META.get('HTTP_AUTHORIZATION', b''),
        'user': request.user.username
    })


urlpatterns = patterns(
    '',
    url(r'^view/$', view),
)


class TestAPITestClient(TestCase):
    urls = 'rest_framework.tests.test_testing'

    def setUp(self):
        self.client = APIClient()

    def test_credentials(self):
        """
        Setting `.credentials()` adds the required headers to each request.
        """
        self.client.credentials(HTTP_AUTHORIZATION='example')
        for _ in range(0, 3):
コード例 #37
0
    (r'^basic/$',
     MockView.as_view(authentication_classes=[BasicAuthentication])),
    (r'^token/$',
     MockView.as_view(authentication_classes=[TokenAuthentication])),
    (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
    (r'^oauth/$',
     MockView.as_view(authentication_classes=[OAuthAuthentication])),
    (r'^oauth-with-scope/$',
     MockView.as_view(authentication_classes=[OAuthAuthentication],
                      permission_classes=[permissions.TokenHasReadWriteScope
                                          ])))

if oauth2_provider is not None:
    urlpatterns += patterns(
        '',
        url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
        url(r'^oauth2-test/$',
            MockView.as_view(authentication_classes=[OAuth2Authentication])),
        url(
            r'^oauth2-with-scope-test/$',
            MockView.as_view(
                authentication_classes=[OAuth2Authentication],
                permission_classes=[permissions.TokenHasReadWriteScope])),
    )


class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.test_authentication'

    def setUp(self):
コード例 #38
0

class AlbumDetail(generics.RetrieveAPIView):
    model = Album
    serializer_class = AlbumSerializer
    lookup_field = 'title'


class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
    model = OptionalRelationModel
    model_serializer_class = serializers.HyperlinkedModelSerializer


urlpatterns = patterns(
    '',
    url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
    url(r'^basic/(?P<pk>\d+)/$',
        BasicDetail.as_view(),
        name='basicmodel-detail'),
    url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(),
        name='anchor-detail'),
    url(r'^manytomany/$',
        ManyToManyList.as_view(),
        name='manytomanymodel-list'),
    url(r'^manytomany/(?P<pk>\d+)/$',
        ManyToManyDetail.as_view(),
        name='manytomanymodel-detail'),
    url(r'^posts/(?P<pk>\d+)/$',
        BlogPostDetail.as_view(),
        name='blogpost-detail'),
    url(r'^comments/$',
コード例 #39
0
class ResourceInstance(APIView):
    pass


class NestedResourceRoot(APIView):
    pass


class NestedResourceInstance(APIView):
    pass


urlpatterns = patterns(
    '',
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.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()),
)


class BreadcrumbTests(TestCase):
    """Tests the breadcrumb functionality used by the HTML renderer."""

    urls = 'rest_framework.tests.breadcrumbs'

    def test_root_breadcrumbs(self):
        url = '/'
コード例 #40
0
class HTMLView(APIView):
    renderer_classes = (BrowsableAPIRenderer, )

    def get(self, request, **kwargs):
        return Response('text')


class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        return Response('text')

urlpatterns = patterns('',
    url(r'^setbyview$', MockViewSettingCharset.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^restframework', include('rest_framework.urls', namespace='rest_framework'))
)


# TODO: Clean tests bellow - remove duplicates with above, better unit testing, ...
class RendererIntegrationTests(TestCase):
    """
    End-to-end testing of renderers using an ResponseMixin on a generic view.
    """

    urls = 'rest_framework.tests.response'
コード例 #41
0
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})


urlpatterns = patterns('',
    (r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])),
    (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
    (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
    (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
    (r'^oauth/$', MockView.as_view(authentication_classes=[OAuthAuthentication])),
    (r'^oauth-with-scope/$', MockView.as_view(authentication_classes=[OAuthAuthentication],
        permission_classes=[permissions.TokenHasReadWriteScope]))
)

if oauth2_provider is not None:
    urlpatterns += patterns('',
        url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
        url(r'^oauth2-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication])),
        url(r'^oauth2-with-scope-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication],
            permission_classes=[permissions.TokenHasReadWriteScope])),
    )


class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.test_authentication'

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
コード例 #42
0
        class Meta:
            model = BasicModel
            fields = ['text']

    class IncorrectlyConfiguredRootView(generics.ListCreateAPIView):
        model = FilterableItem
        filter_class = MisconfiguredFilter
        filter_backend = filters.DjangoFilterBackend

    class FilterClassDetailView(generics.RetrieveAPIView):
        model = FilterableItem
        filter_class = SeveralFieldsFilter
        filter_backend = filters.DjangoFilterBackend

    urlpatterns = patterns('',
        url(r'^(?P<pk>\d+)/$', FilterClassDetailView.as_view(), name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date}
    
    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
        for i in range(10):
            text = chr(i + ord(base_data[0])) * 3  # Produces string 'aaa', 'bbb', etc.
コード例 #43
0
class HTMLView(APIView):
    renderer_classes = (BrowsableAPIRenderer, )

    def get(self, request, **kwargs):
        return Response('text')


class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        return Response('text')

urlpatterns = patterns('',
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^cache$', MockGETView.as_view()),
    url(r'^jsonp/jsonrenderer$', MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
    url(r'^jsonp/nojsonrenderer$', MockGETView.as_view(renderer_classes=[JSONPRenderer])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^api', include('rest_framework.urls', namespace='rest_framework'))
)


class POSTDeniedPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method != 'POST'

コード例 #44
0
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()


def null_view(request):
    pass

urlpatterns = patterns('',
    url(r'^view$', null_view, name='view'),
)


class ReverseTests(TestCase):
    """
    Tests for fully qualified URLs when using `reverse`.
    """
    urls = 'rest_framework.tests.test_reverse'

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get('/view')
        url = reverse('view', request=request)
        self.assertEqual(url, 'http://testserver/view')
コード例 #45
0
ファイル: test_response.py プロジェクト: jia58960/lightforum
    model = BasicModel


class HTMLNewModelView(generics.ListCreateAPIView):
    renderer_classes = (BrowsableAPIRenderer,)
    permission_classes = []
    serializer_class = BasicModelSerializer
    model = BasicModel


new_model_viewset_router = routers.DefaultRouter()
new_model_viewset_router.register(r'', HTMLNewModelViewSet)


urlpatterns = patterns('',
    url(r'^setbyview$', MockViewSettingContentType.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^html_new_model$', HTMLNewModelView.as_view()),
    url(r'^html_new_model_viewset', include(new_model_viewset_router.urls)),
    url(r'^restframework', include('rest_framework.urls', namespace='rest_framework'))
)


# TODO: Clean tests bellow - remove duplicates with above, better unit testing, ...
class RendererIntegrationTests(TestCase):
    """
    End-to-end testing of renderers using an ResponseMixin on a generic view.
    """
コード例 #46
0
    model = Photo
    model_serializer_class = PhotoSerializer


class AlbumDetail(generics.RetrieveAPIView):
    model = Album


class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
    model = OptionalRelationModel
    model_serializer_class = serializers.HyperlinkedModelSerializer


urlpatterns = patterns(
    "",
    url(r"^basic/$", BasicList.as_view(), name="basicmodel-list"),
    url(r"^basic/(?P<pk>\d+)/$", BasicDetail.as_view(), name="basicmodel-detail"),
    url(r"^anchor/(?P<pk>\d+)/$", AnchorDetail.as_view(), name="anchor-detail"),
    url(r"^manytomany/$", ManyToManyList.as_view(), name="manytomanymodel-list"),
    url(r"^manytomany/(?P<pk>\d+)/$", ManyToManyDetail.as_view(), name="manytomanymodel-detail"),
    url(r"^posts/(?P<pk>\d+)/$", BlogPostDetail.as_view(), name="blogpost-detail"),
    url(r"^comments/$", BlogPostCommentListCreate.as_view(), name="blogpostcomment-list"),
    url(r"^comments/(?P<pk>\d+)/$", BlogPostCommentDetail.as_view(), name="blogpostcomment-detail"),
    url(r"^albums/(?P<title>\w[\w-]*)/$", AlbumDetail.as_view(), name="album-detail"),
    url(r"^photos/$", PhotoListCreate.as_view(), name="photo-list"),
    url(r"^optionalrelation/(?P<pk>\d+)/$", OptionalRelationDetail.as_view(), name="optionalrelationmodel-detail"),
)


class TestBasicHyperlinkedView(TestCase):
    urls = "rest_framework.tests.hyperlinkedserializers"
コード例 #47
0
        serializer_class = FilterableItemSerializer
        filter_fields = ['decimal', 'date']
        filter_backends = (filters.DjangoFilterBackend, )

    class GetQuerysetView(generics.ListCreateAPIView):
        serializer_class = FilterableItemSerializer
        filter_class = SeveralFieldsFilter
        filter_backends = (filters.DjangoFilterBackend, )

        def get_queryset(self):
            return FilterableItem.objects.all()

    urlpatterns = patterns(
        '',
        url(r'^(?P<pk>\d+)/$',
            FilterClassDetailView.as_view(),
            name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
        url(r'^get-queryset/$',
            GetQuerysetView.as_view(),
            name='get-queryset-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {
            'id': obj.id,
            'text': obj.text,
            'decimal': obj.decimal,
            'date': obj.date
コード例 #48
0
        filter_kwargs = {'user': user_pk, 'slug': bucket_slug}

        try:
            obj = _get_object_or_404(queryset, **filter_kwargs)
        except (TypeError, ValueError):
            return Http404

        self.check_object_permissions(self.request, obj)

        return obj


urlpatterns = patterns(
    'django.contrib.auth.views',

    #url(r'^$', ServeView.as_view(), name=''),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/content/(?P<content_path>.*)$',
        bucket_content_nginx,
        name='extra_serve_bucket_content'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/$',
        BucketUpdateUsersRoView.as_view(),
        name='extra_serve_bucket_update_users_ro'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/add/$',
        BucketM2MAddView.as_view(model=Bucket), {'m2m_field': 'users_ro'},
        name='extra_serve_bucket_update_users_ro_add'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/remove/$',
        BucketM2MRemoveView.as_view(model=Bucket), {'m2m_field': 'users_ro'},
        name='extra_serve_bucket_update_users_ro_remove'),
)
コード例 #49
0
    class FilterFieldsQuerysetView(generics.ListCreateAPIView):
        queryset = FilterableItem.objects.all()
        serializer_class = FilterableItemSerializer
        filter_fields = ['decimal', 'date']
        filter_backends = (filters.DjangoFilterBackend,)

    class GetQuerysetView(generics.ListCreateAPIView):
        serializer_class = FilterableItemSerializer
        filter_class = SeveralFieldsFilter
        filter_backends = (filters.DjangoFilterBackend,)

        def get_queryset(self):
            return FilterableItem.objects.all()

    urlpatterns = patterns('',
        url(r'^(?P<pk>\d+)/$', FilterClassDetailView.as_view(), name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
        url(r'^get-queryset/$', GetQuerysetView.as_view(),
            name='get-queryset-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date}

    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
コード例 #50
0
ファイル: test_filters.py プロジェクト: GVRGowtham/mozillians
        queryset = FilterableItem.objects.all()
        serializer_class = FilterableItemSerializer
        filter_fields = ["decimal", "date"]
        filter_backends = (filters.DjangoFilterBackend,)

    class GetQuerysetView(generics.ListCreateAPIView):
        serializer_class = FilterableItemSerializer
        filter_class = SeveralFieldsFilter
        filter_backends = (filters.DjangoFilterBackend,)

        def get_queryset(self):
            return FilterableItem.objects.all()

    urlpatterns = patterns(
        "",
        url(r"^(?P<pk>\d+)/$", FilterClassDetailView.as_view(), name="detail-view"),
        url(r"^$", FilterClassRootView.as_view(), name="root-view"),
        url(r"^get-queryset/$", GetQuerysetView.as_view(), name="get-queryset-view"),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {"id": obj.id, "text": obj.text, "decimal": obj.decimal, "date": obj.date}

    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ("a", Decimal("0.25"), datetime.date(2012, 10, 8))
        for i in range(10):
コード例 #51
0
ファイル: reverse.py プロジェクト: BryceBrown/LinkstrDjango
from __future__ import unicode_literals
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse

factory = RequestFactory()


def null_view(request):
    pass


urlpatterns = patterns("", url(r"^view$", null_view, name="view"))


class ReverseTests(TestCase):
    """
    Tests for fully qualified URLs when using `reverse`.
    """

    urls = "rest_framework.tests.reverse"

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get("/view")
        url = reverse("view", request=request)
        self.assertEqual(url, "http://testserver/view")
コード例 #52
0
from __future__ import unicode_literals
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse

factory = RequestFactory()


def null_view(request):
    pass


urlpatterns = patterns(
    '',
    url(r'^view$', null_view, name='view'),
)


class ReverseTests(TestCase):
    """
    Tests for fully qualifed URLs when using `reverse`.
    """
    urls = 'rest_framework.tests.reverse'

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get('/view')
        url = reverse('view', request=request)
        self.assertEqual(url, 'http://testserver/view')
コード例 #53
0
        'auth': request.META.get('HTTP_AUTHORIZATION', b''),
        'user': request.user.username
    })


@api_view(['GET', 'POST'])
def session_view(request):
    active_session = request.session.get('active_session', False)
    request.session['active_session'] = True
    return Response({
        'active_session': active_session
    })


urlpatterns = patterns('',
    url(r'^view/$', view),
    url(r'^session-view/$', session_view),
)


class TestAPITestClient(TestCase):
    urls = 'rest_framework.tests.test_testing'

    def setUp(self):
        self.client = APIClient()

    def test_credentials(self):
        """
        Setting `.credentials()` adds the required headers to each request.
        """
        self.client.credentials(HTTP_AUTHORIZATION='example')
コード例 #54
0

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def permission_denied(request):
    raise PermissionDenied()


@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def not_found(request):
    raise Http404()


urlpatterns = patterns('',
    url(r'^$', example),
    url(r'^permission_denied$', permission_denied),
    url(r'^not_found$', not_found),
)


class TemplateHTMLRendererTests(TestCase):
    urls = 'rest_framework.tests.test_htmlrenderer'

    def setUp(self):
        """
        Monkeypatch get_template
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name, dirs=None):