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: 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 #2
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 #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: 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 #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: test_renderers.py From django-rest-framework-datatables with MIT License | 5 votes |
def test_render(self): obj = {'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = APIView() request = view.initialize_request( self.factory.get('/api/foo/?format=datatables&draw=2') ) content = renderer.render(obj, 'application/json', {'request': request, 'view': view}) expected = { 'recordsTotal': 4, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}], 'draw': 2 } self.assertEquals(json.loads(content.decode('utf-8')), expected)
Example #12
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 #13
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 5 votes |
def test_render_no_pagination2(self): obj = {'results': [{'foo': 'bar'}, {'spam': 'eggs'}]} renderer = DatatablesRenderer() view = APIView() 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': 2, 'recordsFiltered': 2, 'data': [{'foo': 'bar'}, {'spam': 'eggs'}], 'draw': 1 } self.assertEquals(json.loads(content.decode('utf-8')), expected)
Example #14
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 5 votes |
def test_render_no_pagination1_1(self): obj = [{'foo': 'bar'}] renderer = DatatablesRenderer() view = APIView() request = view.initialize_request( self.factory.get('/api/foo.datatables?draw=1') ) content = renderer.render(obj, 'application/json', {'request': request, 'view': view}) expected = { 'recordsTotal': 1, 'recordsFiltered': 1, 'data': [{'foo': 'bar'}], 'draw': 1 } self.assertEquals(json.loads(content.decode('utf-8')), expected)
Example #15
Source File: test_renderers.py From django-rest-framework-datatables with MIT License | 5 votes |
def test_render_no_pagination1(self): obj = [{'foo': 'bar'}] renderer = DatatablesRenderer() view = APIView() 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': 1, 'recordsFiltered': 1, 'data': [{'foo': 'bar'}], 'draw': 1 } self.assertEquals(json.loads(content.decode('utf-8')), expected)
Example #16
Source File: test_filters.py From course-discovery with GNU Affero General Public License v3.0 | 5 votes |
def test_get_request_filters_with_falsey_values(self): """ Verify the method does not strip valid falsey values. """ request = APIRequestFactory().get('/?q=&test=0') request = APIView().initialize_request(request) filters = HaystackRequestFilterMixin.get_request_filters(request) assert 'q' not in filters assert filters.get('test') == '0'
Example #17
Source File: test_filters.py From course-discovery with GNU Affero General Public License v3.0 | 5 votes |
def test_get_request_filters(self): """ Verify the method removes query parameters with empty values """ request = APIRequestFactory().get('/?q=') request = APIView().initialize_request(request) filters = HaystackRequestFilterMixin.get_request_filters(request) assert filters == {}
Example #18
Source File: indy_views.py From indy-ssivc-tutorial with Apache License 2.0 | 5 votes |
def post(self, request, *args, **kwargs): """ Processes a claim definition and responds with a claim request which can then be used to submit a claim. Example request payload: ```json { 'claim_offer': <schema offer json>, 'claim_def': <claim definition json> } ``` returns: indy sdk claim request json """ claimDef = request.body.decode('utf-8') claimDefProcesser = ClaimDefProcesser(claimDef) claimRequest = claimDefProcesser.GenerateClaimRequest() return JsonResponse(json.loads(claimRequest)) # ToDo: # * Refactor the saving process to use serializers, etc. # ** Make it work with generics.GenericAPIView # ** Using APIView for the moment so a serializer_class does not need to be defined; # as we manually processing things for the moment.
Example #19
Source File: generators.py From Dailyfresh-B2C with Apache 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 cls = getattr(callback, 'cls', None) return (cls is not None) and issubclass(cls, APIView)
Example #20
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"')
Example #21
Source File: views.py From Django-Angular-Ionic 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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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)