本文整理汇总了Python中rest_framework.views.APIView方法的典型用法代码示例。如果您正苦于以下问题:Python views.APIView方法的具体用法?Python views.APIView怎么用?Python views.APIView使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.views
的用法示例。
在下文中一共展示了views.APIView方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_view_introspector
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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')
示例2: get_api_root_view
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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()
示例3: test_should_not_cache_for_non_json_responses
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)
示例4: test_should_not_cache_if_waffled
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)
示例5: test_render_no_pagination3
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)
示例6: test_render_extra_json_attr_missing
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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.")
示例7: test_render_extra_json_attr_not_callable
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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.")
示例8: test_render_extra_json_clashes
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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")
示例9: post
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)
示例10: setUp
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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()
示例11: filter_api_view_callbacks
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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
示例12: setUp
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)),
)
示例13: is_api_view
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)
示例14: upgrade_to_api_request
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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
示例15: _is_drf_view
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import APIView [as 别名]
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)