Python rest_framework.views 模块,APIView() 实例源码

我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用rest_framework.views.APIView()

项目:django-openapi-gen    作者:Ecognize    | 项目源码 | 文件源码
def SwaggerRequestMethodMaker(model = None):
    def model_handler(self, request, *args, **kwargs):
        data = kwargs.get('data', None)
        resp = model

        return Response(resp, status = status.HTTP_200_OK)

    def empty_handler(self, request, *args, **kwargs):
        data = kwargs.get('data', None)
        resp = None

        return Response(resp, status = status.HTTP_200_OK)

    if model:
        return model_handler
    else:
        return empty_handler

# make named APIView class with specified methods
项目:drf_tweaks    作者:ArabellaTech    | 项目源码 | 文件源码
def get_swagger_schema_api_view(permissions=None, renderers=None):
    if not permissions:
        permissions = [SwaggerAdminPermission]

    if not renderers:
        renderers = [VersionedOpenAPIRenderer]

    class SwaggerSchemaView(APIView):
        permission_classes = permissions
        _ignore_model_permissions = True
        exclude_from_schema = True
        renderer_classes = renderers

        def get(self, request):
            generator = SwaggerSchemaGenerator()
            # disable versioning when schema is being generated
            request.version = None
            schema = generator.get_schema(request=request)
            return Response(schema)

    return SwaggerSchemaView.as_view()
项目:py2swagger    作者:Arello-Mobile    | 项目源码 | 文件源码
def get_view_introspector(api):
    """
    Creates view introspector based on api

    :param api:
    :rtype: BaseViewIntrospector
    """
    callback = api['callback']

    def inmodule(callback, module_name):
        return callback.__module__ == module_name

    map = (
        (issubclass, ViewSetMixin, ViewSetIntrospector),
        (inmodule, 'rest_framework.decorators', WrappedApiViewIntrospector),
        (issubclass, APIView, ApiViewIntrospector),
    )

    for f, param, introspector_class in map:
        if f(callback, param):
            return introspector_class(**api)

    raise IntrospectorException('View introspector not recognized')
项目:django-learning    作者:adoggie    | 项目源码 | 文件源码
def _get(self,request,*args,**kwargs):
        """
        ????get() ,?????Name? xxx_class???????????????
        ???? {status,errcode,errmsg,result} ?????????
        ??????APIView??????,???????????ListViewAPI
        """
        # if  request.user.is_authenticated:
        #   return Response({'status':0})  #????????
        ser = SerializerDBTable( self.get_queryset(),many=True)
        data = ser.data
        return Response(data)

        #??????
        page = PageNumberPagination()
        page.paginate_queryset(self.queryset.all()[:200],request)
        return page.get_paginated_response(ser.data)


        return Response({'result':data})
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_obj(self, request: t.Optional[Request], view: t.Optional[APIView]) -> t.Any:
        return None

    # noinspection PyUnusedLocal,PyProtectedMember
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_title(self,
                  request: t.Optional[Request],
                  view: t.Optional[APIView],
                  obj: t.Optional[t.Any]=None) -> str:
        return self.title or self.model._meta.verbose_name
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def determine_metadata(self, request: Request, view: t.Optional[APIView]=None, obj: t.Any=None):
        self.request = request
        self.view = view
        self.obj = obj or self.get_obj(request, view)

        if isinstance(self.model, str):
            # noinspection PyUnresolvedReferences
            self.model = django.apps.apps.get_model(*self.model.split('.'))

        # noinspection PyProtectedMember,PyUnresolvedReferences
        return {
            'title': self.get_title(request, view, obj),
            'description': view.get_view_description() if view else '',
            'fields': self.get_meta(),
        }
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_obj(self, request: t.Optional[Request], view: t.Optional[APIView]) -> t.Any:
        return None

    # noinspection PyUnusedLocal,PyProtectedMember
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_title(self,
                  request: t.Optional[Request],
                  view: t.Optional[APIView],
                  obj: t.Optional[t.Any]=None) -> str:
        return self.title or ''
项目:drf-swagger-extras    作者:ssaavedra    | 项目源码 | 文件源码
def test_decorator_wrong_schema_obj_element(self):
        self.assertRaises(Exception,
                          responds,
                          500,
                          "On server failure",
                          schema={
                              'wrong-element': APIView,
                          })
项目:drf-swagger-extras    作者:ssaavedra    | 项目源码 | 文件源码
def test_decorator_status_default(self):

        @responds(None, "Test", schema={})
        class TestView(APIView):
            def get(self, request, *args, **kwargs):
                "Example get comment"
                return Response()

        schema_generator = SchemaGenerator(
            title='Test View',
            patterns=[url('^/different-example/$',
                          TestView.as_view(),
                          name='example')]
        )
        schema = generate_swagger_object(schema_generator.get_schema())
        expected = {
            'info': {'title': 'Test View', 'version': ''},
            'swagger': '2.0',
            'paths': {
                '/different-example/': {
                    'get': {
                        'operationId': 'read',
                        'parameters': [],
                        'tags': ['different-example'],
                        'produces': ['application/json', 'application/xml'],
                        'responses': {'default': {'description': 'Test'}}
                    }
                }
            }
        }

        self.assertEquals(to_dict(schema), expected)
项目:drf-swagger-extras    作者:ssaavedra    | 项目源码 | 文件源码
def test_nondecorated_view_works(self):
        class TestView(APIView):
            def get(self, request, *args, **kwargs):
                "Example get comment"
                return Response()

        schema_generator = SchemaGenerator(
            title='Test View',
            patterns=[url('^/different-example/$',
                          TestView.as_view(),
                          name='example')]
        )

        schema = generate_swagger_object(schema_generator.get_schema())

        print(schema)

        expected = {
            'swagger': '2.0',
            'info': {
                'title': 'Test View',
                'version': ''
            },
            'paths': {
                '/different-example/': {
                    'get': {
                        'operationId': 'read',
                        'tags': ['different-example'],
                        'parameters': [],
                        'responses': None,
                        'produces': ['application/json', 'application/xml']
                    }
                }
            }
        }
        self.assertEquals(to_dict(schema), expected)
项目:django-validator    作者:romain-li    | 项目源码 | 文件源码
def __call__(self, func):
        if hasattr(func, '__params__'):
            func.__params__.append(self)
            return func

        @wraps(func)
        def _decorator(*args, **kwargs):
            if len(args) < 1:
                # Call function immediately, maybe raise an error is better.
                return func(*args, **kwargs)

            extra_kwargs = None
            if isinstance(args[0], View):
                request = args[0].request
                # Update the kwargs from Django REST framework's APIView class
                if isinstance(args[0], APIView):
                    extra_kwargs = args[0].kwargs

            else:
                # Find the first request object
                for arg in args:
                    if isinstance(arg, (RestRequest, HttpRequest)):
                        request = arg
                        break
                else:
                    request = args[0]

            if request:
                # Checkout all the params first.
                for _param in _decorator.__params__:
                    _param._parse(request, kwargs, extra_kwargs)
                # Validate after all the params has checked out, because some validators needs all the params.
                for _param in _decorator.__params__:
                    for validator in _param.validators:
                        validator(_param.related_name, kwargs, _param.verbose_name)

            return func(*args, **kwargs)

        _decorator.__params__ = [self]
        return _decorator
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def is_api_view(callback):
    """
    Return `True` if the given view callback is a REST framework view/viewset.
    """
    cls = getattr(callback, 'cls', None)
    return (cls is not None) and issubclass(cls, APIView)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def get_view_name(view_cls, suffix=None):
    ''' Override Django REST framework's name for the base API class '''
    # The base API class should inherit directly from APIView. We can't use
    # issubclass() because ViewSets also inherit (indirectly) from APIView.
    try:
        if inspect.getmro(view_cls)[1] is rest_framework_views.APIView:
            return 'KoBo Api' # awkward capitalization for consistency
    except KeyError:
        pass
    return rest_framework_views.get_view_name(view_cls, suffix)
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def get_api_root_view(self):
        """
        Return a view to use as the API root.
        """
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                return Response(ret)

        return APIRoot.as_view()
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_api_root_view(self, api_urls):
        class APIRoot(APIView):
            def get(self, request, format=None):
                return Response({})
        return APIRoot.as_view()
项目:profiles-rest-api    作者:LondonAppDevVideos1    | 项目源码 | 文件源码
def get(self, request, format=None):
        """Returns a list of APIView features."""

        an_apiview = [
            'Uses HTTP methods as function (get, post, patch, put, delete)',
            'It is similar to a traditional Django view',
            'Gives you the most control over your logic',
            'Is mapped manually to URLs'
        ]

        return Response({'message': 'Hello!', 'an_apiview': an_apiview})
项目:profiles-rest-api    作者:LondonAppDevVideos1    | 项目源码 | 文件源码
def create(self, request):
        """Use the ObtainAuthToken APIView to validate and create a token."""

        return ObtainAuthToken().post(request)
项目:drf-swagger-customization    作者:androiz    | 项目源码 | 文件源码
def get_swagger_view(title=None, url=None, patterns=None, urlconf=None):
    """
    Returns schema view which renders Swagger/OpenAPI.
    """
    class SwaggerSchemaView(APIView):
        _ignore_model_permissions = True
        exclude_from_schema = True
        permission_classes = [AllowAny]
        renderer_classes = [
            CoreJSONRenderer,
            CustomOpenAPIRenderer,
            renderers.SwaggerUIRenderer
        ]

        def get(self, request):
            generator = SchemaGenerator(
                title=title,
                url=url,
                patterns=patterns,
                urlconf=urlconf
            )
            schema = generator.get_schema(request=request)
            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document'
                )
            return Response(schema)
    return SwaggerSchemaView.as_view()
项目:py2swagger    作者:Arello-Mobile    | 项目源码 | 文件源码
def setUp(self):
        class FuzzyApiView(APIView):
            def get(self, request):
                pass

        class ShinyApiView(APIView):
            def get(self, request):
                pass

        api_fuzzy_url_patterns = patterns(
            '', url(r'^item/$', FuzzyApiView.as_view(), name='find_me'))
        api_shiny_url_patterns = patterns(
            '', url(r'^item/$', ShinyApiView.as_view(), name='hide_me'))

        fuzzy_app_urls = patterns(
            '', url(r'^api/', include(api_fuzzy_url_patterns,
                                      namespace='api_fuzzy_app')))
        shiny_app_urls = patterns(
            '', url(r'^api/', include(api_shiny_url_patterns,
                                      namespace='api_shiny_app')))

        self.project_urls = patterns(
            '',
            url('my_fuzzy_app/', include(fuzzy_app_urls)),
            url('my_shiny_app/', include(shiny_app_urls)),
        )
项目:py2swagger    作者:Arello-Mobile    | 项目源码 | 文件源码
def filter_api_view_callbacks(cls, url_pattern):
        if not hasattr(url_pattern, 'callback'):
            return

        if hasattr(url_pattern.callback, 'cls') and issubclass(url_pattern.callback.cls, APIView):
            return url_pattern.callback.cls
项目:deux    作者:robinhood    | 项目源码 | 文件源码
def extract_body(self, request):
        """
        Extract request body by coercing the request to a Django Rest
        Framework Request.

        :params request: The request to extract the body from.
        :returns: Returns the items in the requests body.
        """
        if not isinstance(request, DRFRequest):
            request = APIView().initialize_request(request)
        # our custom authorization view is already using DRF
        return request.data.items() if request.data else []
项目:djangorestframework-blueprint    作者:odoku    | 项目源码 | 文件源码
def is_api_view(view):
    return hasattr(view, 'cls') and issubclass(view.cls, APIView)
项目:drf-swagger-extras    作者:ssaavedra    | 项目源码 | 文件源码
def get_api_root_view(self, api_urls=None):
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

            view_renderers = list(self.root_renderers)
            schema_media_types = []

            if api_urls and self.schema_title:
                view_renderers += list(self.schema_renderers)
                schema_generator = SchemaGenerator(
                    title=self.schema_title,
                    url=self.schema_url,
                    patterns=api_urls
                )
            schema_media_types = [
                renderer.media_type
                for renderer in self.schema_renderers
            ]

        class APIRoot(views.APIView):
            _ignore_model_permissions = True
            renderer_classes = view_renderers

            def get(self, request, *args, **kwargs):
                if request.accepted_renderer.media_type in schema_media_types:
                    # Return a schema response.
                    schema = schema_generator.get_schema(request)
                    if schema is None:
                        raise exceptions.PermissionDenied()
                    return Response(schema)

                # Return a plain {"name": "hyperlink"} response.
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist,
                        # only detail routes.
                        continue

                return Response(ret)

        return APIRoot.as_view()
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def get_breadcrumbs(url, request=None):
    """
    Given a url returns a list of breadcrumbs, which are each a
    tuple of (name, url).
    """
    from rest_framework.reverse import preserve_builtin_query_params
    from rest_framework.views import APIView

    def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen):
        """
        Add tuples of (name, url) to the breadcrumbs list,
        progressively chomping off parts of the url.
        """
        try:
            (view, unused_args, unused_kwargs) = resolve(url)
        except Exception:
            pass
        else:
            # Check if this is a REST framework view,
            # and if so add it to the breadcrumbs
            cls = getattr(view, 'cls', None)
            initkwargs = getattr(view, 'initkwargs', {})
            if cls is not None and issubclass(cls, APIView):
                # Don't list the same view twice in a row.
                # Probably an optional trailing slash.
                if not seen or seen[-1] != view:
                    c = cls(**initkwargs)
                    c.suffix = getattr(view, 'suffix', None)
                    name = c.get_view_name()
                    insert_url = preserve_builtin_query_params(prefix + url, request)
                    breadcrumbs_list.insert(0, (name, insert_url))
                    seen.append(view)

        if url == '':
            # All done
            return breadcrumbs_list

        elif url.endswith('/'):
            # Drop trailing slash off the end and continue to try to
            # resolve more breadcrumbs
            url = url.rstrip('/')
            return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)

        # Drop trailing non-slash off the end and continue to try to
        # resolve more breadcrumbs
        url = url[:url.rfind('/') + 1]
        return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)

    prefix = get_script_prefix().rstrip('/')
    url = url[len(prefix):]
    return breadcrumbs_recursive(url, [], prefix, [])
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def get_breadcrumbs(url, request=None):
    """
    Given a url returns a list of breadcrumbs, which are each a
    tuple of (name, url).
    """
    from rest_framework.reverse import preserve_builtin_query_params
    from rest_framework.settings import api_settings
    from rest_framework.views import APIView

    view_name_func = api_settings.VIEW_NAME_FUNCTION

    def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen):
        """
        Add tuples of (name, url) to the breadcrumbs list,
        progressively chomping off parts of the url.
        """

        try:
            (view, unused_args, unused_kwargs) = resolve(url)
        except Exception:
            pass
        else:
            # Check if this is a REST framework view,
            # and if so add it to the breadcrumbs
            cls = getattr(view, 'cls', None)
            if cls is not None and issubclass(cls, APIView):
                # Don't list the same view twice in a row.
                # Probably an optional trailing slash.
                if not seen or seen[-1] != view:
                    suffix = getattr(view, 'suffix', None)
                    name = view_name_func(cls, suffix)
                    insert_url = preserve_builtin_query_params(prefix + url, request)
                    breadcrumbs_list.insert(0, (name, insert_url))
                    seen.append(view)

        if url == '':
            # All done
            return breadcrumbs_list

        elif url.endswith('/'):
            # Drop trailing slash off the end and continue to try to
            # resolve more breadcrumbs
            url = url.rstrip('/')
            return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)

        # Drop trailing non-slash off the end and continue to try to
        # resolve more breadcrumbs
        url = url[:url.rfind('/') + 1]
        return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)

    prefix = get_script_prefix().rstrip('/')
    url = url[len(prefix):]
    return breadcrumbs_recursive(url, [], prefix, [])
项目:django-rest-framework-mongoengine-example    作者:BurkovBA    | 项目源码 | 文件源码
def get_api_root_view(self):
        # callgraph:
        # HybridRouter.get_urls
        # DefaultRouter.get_urls
        # HybridRouter.get_api_root_view

        # Copy the following block from Default Router
        api_root_dict = {}
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        # In addition to that:
        api_view_urls = self._api_view_urls

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                # In addition to what had been added, now add the APIView urls
                for api_view_key in api_view_urls.keys():
                    # originally was: reverse(api_view_urls[api_view_key].name, request=request, format=format)
                    namespace = request.resolver_match.namespace
                    if namespace:
                        url_name = namespace + ":" + api_view_key
                    try:
                        ret[api_view_key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        continue

                return response.Response(ret)

        return APIRoot.as_view()