Python rest_framework.views.APIView() Examples
The following are 30
code examples of rest_framework.views.APIView().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.views
, or try the search function
.

Example #1
Source File: view.py From py2swagger with MIT License | 6 votes |
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')
Example #2
Source File: routers.py From dynamic-rest with MIT License | 6 votes |
def get_api_root_view(self, **kwargs): """Return API root view, using the global directory.""" class API(views.APIView): _ignore_model_permissions = True def get(self, request, *args, **kwargs): directory_list = get_directory(request) result = OrderedDict() for group_name, url, endpoints, _ in directory_list: if url: result[group_name] = url else: group = OrderedDict() for endpoint_name, url, _, _ in endpoints: group[endpoint_name] = url result[group_name] = group return Response(result) return API.as_view()
Example #3
Source File: test_cache.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
def test_should_not_cache_for_non_json_responses(self): """ Verify that the decorator does not cache if the response is not json """ def key_func(**kwargs): # pylint: disable=unused-argument return 'non_json_cache_key' class TestView(views.APIView): permission_classes = [permissions.AllowAny] renderer_classes = [BrowsableAPIRenderer] # Non-json responses @compressed_cache_response(key_func=key_func) def get(self, request, *args, **kwargs): return Response('test response') view_instance = TestView() view_instance.headers = {} # pylint: disable=attribute-defined-outside-init view_instance.dispatch(request=self.request) # Verify nothing was cached self.assertEqual(cache.get('non_json_cache_key'), None)
Example #4
Source File: test_cache.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
def test_should_not_cache_if_waffled(self, waffle_active): """ Verify that the decorator does not cache the waffle flag is turned off """ def key_func(**kwargs): # pylint: disable=unused-argument return self.cache_response_key class TestView(views.APIView): permission_classes = [permissions.AllowAny] renderer_classes = [JSONRenderer] @compressed_cache_response(key_func=key_func) def get(self, request, *args, **kwargs): return Response('test response') with override_flag('compressed_cache.TestView.get', active=waffle_active): view_instance = TestView() view_instance.headers = {} # pylint: disable=attribute-defined-outside-init view_instance.dispatch(request=self.request) # Verify nothing was cached if waffle_active: self.assertIsNot(cache.get(self.cache_response_key), None) else: self.assertIs(cache.get(self.cache_response_key), None)
Example #5
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 6 votes |
def test_render_no_pagination3(self): obj = {'results': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = APIView() view._datatables_total_count = 4 view._datatables_filtered_count = 2 request = view.initialize_request( self.factory.get('/api/foo/?format=datatables&draw=1') ) content = renderer.render(obj, 'application/json', {'request': request, 'view': view}) expected = { 'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}], 'draw': 1 } self.assertEquals(json.loads(content.decode('utf-8')), expected)
Example #6
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 6 votes |
def test_render_extra_json_attr_missing(self): class TestAPIView(APIView): class Meta: datatables_extra_json = ('test_callback', ) obj = {'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = TestAPIView() request = view.initialize_request( self.factory.get('/api/foo/?format=datatables&draw=2') ) try: renderer.render(obj, 'application/json', {'request': request, 'view': view}) self.assertEqual(True, False, "TypeError expected; did not occur.") except TypeError as e: self.assertEqual(e.__str__(), "extra_json_funcs: test_callback not a view method.")
Example #7
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 6 votes |
def test_render_extra_json_attr_not_callable(self): class TestAPIView(APIView): test_callback = 'gotcha' class Meta: datatables_extra_json = ('test_callback', ) obj = {'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = TestAPIView() request = view.initialize_request( self.factory.get('/api/foo/?format=datatables&draw=2') ) try: renderer.render(obj, 'application/json', {'request': request, 'view': view}) self.assertEqual(True, False, "TypeError expected; did not occur.") except TypeError as e: self.assertEqual(e.__str__(), "extra_json_funcs: test_callback not callable.")
Example #8
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 6 votes |
def test_render_extra_json_clashes(self): class TestAPIView(APIView): def test_callback(self): return "recordsTotal", "this could be bad" class Meta: datatables_extra_json = ('test_callback', ) obj = {'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = TestAPIView() request = view.initialize_request( self.factory.get('/api/foo/?format=datatables&draw=2') ) try: renderer.render(obj, 'application/json', {'request': request, 'view': view}) self.assertEqual(True, False, "Value expected; did not occur.") except ValueError as e: self.assertEqual(e.__str__(), "Duplicate key found: recordsTotal")
Example #9
Source File: views.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def post(self, request): """ Updates quantity for a basket. Note: This only works for single-product baskets. """ if request.basket.is_empty: return self.get_payment_api_response(status=400) basket_line = self._get_first_basket_line() if not basket_line.product.is_enrollment_code_product: return self.get_payment_api_response(status=400) # NOTE: Ideally, we'd inherit FormView; but that doesn't work with APIView form = self._get_basket_line_form(basket_line) if form.is_valid(): form.save() return self._form_valid() return self._form_invalid(form)
Example #10
Source File: test_gzip_decorator.py From polyaxon with Apache License 2.0 | 6 votes |
def setUp(self): super(TestGZip, self).setUp() fake = Faker() class TestView(APIView): @gzip() def get(self, request, *args, **kwargs): """Example to check `Content-Encoding` header is set to 'gzip'.""" return Response(status=200, data=fake.text()) class SubClassTestView(TestView): def get(self, request, *args, **kwargs): """Example to check that no status is set after overriding inherited endpoints.""" return Response(status=200, data=fake.text()) self.view = TestView.as_view() self.subclass_view = SubClassTestView.as_view() self.factory = RequestFactory()
Example #11
Source File: urlparser.py From py2swagger with MIT License | 5 votes |
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
Example #12
Source File: test_urlparser.py From py2swagger with MIT License | 5 votes |
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)), )
Example #13
Source File: utils.py From normandy with Mozilla Public License 2.0 | 5 votes |
def is_api_view(callback): """ Return `True` if the given view callback is a REST framework view/viewset. """ # Avoid import cycle on APIView from rest_framework.views import APIView from normandy.base.api.views import APIRootView cls = getattr(callback, "cls", None) return (cls is not None) and issubclass(cls, APIView) and not issubclass(cls, APIRootView)
Example #14
Source File: tests.py From longclaw with MIT License | 5 votes |
def upgrade_to_api_request(request): # This extra step is required until https://github.com/encode/django-rest-framework/issues/6488 # is resolved class DummyGenericViewsetLike(APIView): lookup_field = 'test' def reverse_action(view, *args, **kwargs): self.assertEqual(kwargs['kwargs']['test'], 1) return '/example/' response = DummyGenericViewsetLike.as_view()(request) view = response.renderer_context['view'] view.request.site = Site.objects.first() return view.request
Example #15
Source File: api_docs.py From django-rest-framework-docs with BSD 2-Clause "Simplified" License | 5 votes |
def _is_drf_view(self, pattern): """ Should check whether a pattern inherits from DRF's APIView """ return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
Example #16
Source File: tools.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
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)
Example #17
Source File: views.py From REST-API with MIT License | 5 votes |
def get_serializer_context(self, *args, **kwargs): return {"request": self.request} # class RegisterAPIView(APIView): # permission_classes = [permissions.AllowAny] # def post(self, request, *args, **kwargs): # if request.user.is_authenticated(): # return Response({'detail': 'You are already registered and are authenticated.'}, status=400) # data = request.data # username = data.get('username') # username or email address # email = data.get('username') # password = data.get('password') # password2 = data.get('password2') # qs = User.objects.filter( # Q(username__iexact=username)| # Q(email__iexact=username) # ) # if password != password2: # return Response({"password": "Password must match."}, status=401) # if qs.exists(): # return Response({"detail": "This user already exists"}, status=401) # else: # user = User.objects.create(username=username, email=email) # user.set_password(password) # user.save() # # payload = jwt_payload_handler(user) # # token = jwt_encode_handler(payload) # # response = jwt_response_payload_handler(token, user, request=request) # # return Response(response, status=201) # return Response({'detail': "Thank you for registering. Please verify your email."}, status=201) # return Response({"detail": "Invalid Request"}, status=400)
Example #18
Source File: views.py From byob-profiles-rest-api-docker with MIT License | 5 votes |
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})
Example #19
Source File: views.py From byob-profiles-rest-api-docker with MIT License | 5 votes |
def create(self, request): """Use the ObtainAuthToken APIView to validate and create a token.""" return ObtainAuthToken().post(request)
Example #20
Source File: test_django_view_consumer.py From djangochannelsrestframework with MIT License | 5 votes |
def test_view_as_consumer(): results = {} class TestView(APIView): def get(self, request, format=None): results["TestView-get"] = True return Response(["test1", "test2"]) # Test a normal connection communicator = WebsocketCommunicator( view_as_consumer(TestView.as_view()), "/testws/" ) connected, _ = await communicator.connect() assert connected await communicator.send_json_to({"action": "retrieve", "request_id": 1}) response = await communicator.receive_json_from() assert "TestView-get" in results assert response == { "errors": [], "data": ["test1", "test2"], "action": "retrieve", "response_status": 200, "request_id": 1, }
Example #21
Source File: test_utils.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 5 votes |
def test_get_resource_name(): view = APIView() context = {'view': view} with override_settings(JSON_API_FORMAT_TYPES=None): assert 'APIViews' == utils.get_resource_name(context), 'not formatted' context = {'view': view} with override_settings(JSON_API_FORMAT_TYPES='dasherize'): assert 'api-views' == utils.get_resource_name(context), 'derived from view' view.model = get_user_model() assert 'users' == utils.get_resource_name(context), 'derived from view model' view.resource_name = 'custom' assert 'custom' == utils.get_resource_name(context), 'manually set on view' view.response = Response(status=403) assert 'errors' == utils.get_resource_name(context), 'handles 4xx error' view.response = Response(status=500) assert 'errors' == utils.get_resource_name(context), 'handles 500 error' view = GenericAPIView() view.serializer_class = ResourceSerializer context = {'view': view} assert 'users' == utils.get_resource_name(context), 'derived from serializer' view.serializer_class.Meta.resource_name = 'rcustom' assert 'rcustom' == utils.get_resource_name(context), 'set on serializer' view = GenericAPIView() view.serializer_class = NonModelResourceSerializer context = {'view': view} assert 'users' == utils.get_resource_name(context), 'derived from non-model serializer'
Example #22
Source File: views.py From byob-profiles-rest-api with MIT License | 5 votes |
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})
Example #23
Source File: views.py From byob-profiles-rest-api with MIT License | 5 votes |
def create(self, request): """Use the ObtainAuthToken APIView to validate and create a token.""" return ObtainAuthToken().post(request)
Example #24
Source File: routers.py From gro-api with GNU General Public License v2.0 | 5 votes |
def get_api_root_view(self): api_root_dict = {} list_name = self.routes[0].name for prefix, _, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) api_view_urls = self._api_view_urls class APIRoot(APIView): _ignore_model_permissions = True allow_on_unconfigured_farm = True def get(self, request, **kwargs): ret = {} for key, url_name in api_root_dict.items(): ret[key] = reverse( url_name, request=request, format=kwargs.pop('format', None) ) for api_view_key in api_view_urls.keys(): ret[api_view_key] = reverse( api_view_urls[api_view_key].name, request=request, format=kwargs.pop('format', None) ) return Response(OrderedDict(sorted(ret.items()))) return APIRoot.as_view()
Example #25
Source File: middleware.py From gro-api with GNU General Public License v2.0 | 5 votes |
def __init__(self): if system_layout.current_value is not None: raise MiddlewareNotUsed() class FarmNotConfiguredView(APIView): permission_classes = (AllowAny, ) def get(self, request): raise FarmNotConfiguredError() post = get put = get patch = get delete = get self.view = FarmNotConfiguredView.as_view()
Example #26
Source File: test_pagination.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def _get_request(self, *args, **kwargs): req = self.factory.get(*args, **kwargs) return APIView().initialize_request(req)
Example #27
Source File: __init__.py From rssant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _make_view(self, group): method_maps = {} method_meta = {} for f, url, methods, params, returns in group: for method in methods: if method in method_maps: raise ValueError(f'duplicated method {method} of {url}') m = self._make_method(method, f, params, returns) method_maps[method] = m method_meta[method] = f, url, params, returns class RestApiView(APIView): if self.permission_classes: permission_classes = self.permission_classes schema = RestViewSchema(method_meta) if 'GET' in method_maps: get = method_maps['GET'] if 'POST' in method_maps: post = method_maps['POST'] if 'PUT' in method_maps: put = method_maps['PUT'] if 'DELETE' in method_maps: delete = method_maps['DELETE'] if 'PATCH' in method_maps: patch = method_maps['PATCH'] return RestApiView.as_view()
Example #28
Source File: test_forms.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_from_request(self): request = factory.post('/', json.dumps({'g': _geom}), content_type='application/json') view = APIView() request = view.initialize_request(request) view.initial(request) form = forms.RasterQueryForm.from_request(request) self.assertTrue(form.is_valid()) geom = geos.GEOSGeometry(json.dumps(_geom)) self.assertEqual(form.cleaned_data['g'], geom.ogr)
Example #29
Source File: test_cache.py From course-discovery with GNU Affero General Public License v3.0 | 5 votes |
def test_should_handle_getting_uncompressed_response_from_cache(self): """ Verify that the decorator correctly returns uncompressed responses """ def key_func(**kwargs): # pylint: disable=unused-argument return self.cache_response_key class TestView(views.APIView): permission_classes = [permissions.AllowAny] renderer_classes = [JSONRenderer] @compressed_cache_response(key_func=key_func) def get(self, request, *args, **kwargs): return Response('test response') view_instance = TestView() view_instance.headers = {} # pylint: disable=attribute-defined-outside-init uncompressed_cached_response = Response('cached test response') view_instance.finalize_response(request=self.request, response=uncompressed_cached_response) uncompressed_cached_response.render() response_triple = ( uncompressed_cached_response.rendered_content, uncompressed_cached_response.status_code, uncompressed_cached_response._headers.copy(), # pylint: disable=protected-access ) cache.set(self.cache_response_key, response_triple) response = view_instance.dispatch(request=self.request) self.assertEqual(response.content.decode('utf-8'), '"cached test response"')
Example #30
Source File: test_cache.py From course-discovery with GNU Affero General Public License v3.0 | 5 votes |
def test_should_handle_getting_compressed_response_from_cache(self): """ Verify that the decorator correctly returns compressed responses """ def key_func(**kwargs): # pylint: disable=unused-argument return self.cache_response_key class TestView(views.APIView): permission_classes = [permissions.AllowAny] renderer_classes = [JSONRenderer] @compressed_cache_response(key_func=key_func) def get(self, request, *args, **kwargs): return Response('test response') view_instance = TestView() view_instance.headers = {} # pylint: disable=attribute-defined-outside-init compressed_cached_response = Response('compressed cached test response') view_instance.finalize_response(request=self.request, response=compressed_cached_response) compressed_cached_response.render() # Rendered content is compressed before response goes into the cache response_triple = ( zlib.compress(compressed_cached_response.rendered_content), compressed_cached_response.status_code, compressed_cached_response._headers.copy(), # pylint: disable=protected-access ) cache.set(self.cache_response_key, response_triple) response = view_instance.dispatch(request=self.request) self.assertEqual(response.content.decode('utf-8'), '"compressed cached test response"')