本文整理汇总了Python中rest_framework.request.Request类的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_empty_slug_request_m2m
def test_empty_slug_request_m2m(self):
class ExampleSerializer(serializers.ModelSerializer):
my_m2mfield = serializers.SlugRelatedField(many=True, slug_field='username', queryset=User.objects.all())
class Meta:
model = models.MyModel
serializer = ExampleSerializer({'content': 'a','my_m2mfield':[]})
factory = APIRequestFactory()
content = json.dumps(serializer.data)
content_type = 'application/json'
post_data = {
api_settings.FORM_CONTENT_OVERRIDE: content,
api_settings.FORM_CONTENTTYPE_OVERRIDE: content_type
}
request = factory.post('/', data=post_data)
# tbd: try another type of basic request
# request = urllib2.Request('/', content, {'Content-Type': 'application/json'})
request = DRFRequest(request)
request.parsers = (JSONParser(), )
serializer = ExampleSerializer(data=request.data)
self.assertTrue(serializer.is_valid())
self.assertTrue(isinstance(serializer.validated_data['my_m2mfield'],list))
self.assertEqual(serializer.validated_data, {'content': u'a', 'my_m2mfield': []})
obj = serializer.create(serializer.validated_data)
self.assertEqual(obj.content, 'a')
self.assertEqual(len(obj.my_m2mfield.all()), 0)
示例2: test_read_write_hyperlinked_collection_property
def test_read_write_hyperlinked_collection_property(self):
request = Request(make_dummy_request())
request._user = User(is_superuser=True)
context = {"request": request}
serializer = ProjectSerializer(self.project, context=context)
field = serializer.get_fields()["notes"]
property_serializer = HydraPropertySerializer(field, "notes", "projectns:", self.project, context=context)
supported_operations = property_serializer.data.get("property").get("hydra:supportedOperation")
self.assertEqual(len(supported_operations), 2)
create_operation, = [op for op in supported_operations if op.get("hydra:method") == "POST"]
self.assertDictEqual(
dict(create_operation),
{
"@id": "_:project_note_create",
"@type": "hydra:CreateResourceOperation",
"label": "Create a note for this project.",
"description": None,
"hydra:method": "POST",
"hydra:expects": "projectns:Note",
"hydra:returns": "projectns:Note",
"hydra:possibleStatus": [],
},
)
示例3: test_multiple_shared_works
def test_multiple_shared_works(self):
request = RequestFactory().post(
"/api",
HTTP_AUTHORIZATION="mkt-shared-secret "
"[email protected],56b6f1a3dd735d962c56"
"ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb"
"9c68c31b3371aa8130317815c89e5072e31bb94b4"
"121c5c165f3515838d4d6c60c4,165d631d3c3045"
"458b4516242dad7ae",
)
drf_request = Request(request)
# Start with an AnonymousUser on the request, because that's a classic
# situation: we already went through a middleware, it didn't find a
# session cookie, if set request.user = AnonymousUser(), and now we
# are going through the authentication code in the API.
request.user = AnonymousUser()
# Call middleware as they would normally be called.
RedirectPrefixedURIMiddleware().process_request(request)
RestSharedSecretMiddleware().process_request(request)
RestOAuthMiddleware().process_request(request)
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication(),
)
eq_(drf_request.user, self.profile.user)
eq_(drf_request._request.user, self.profile.user)
eq_(drf_request.user.is_authenticated(), True)
eq_(drf_request._request.user.is_authenticated(), True)
eq_(drf_request.amo_user.pk, self.profile.pk)
eq_(drf_request._request.amo_user.pk, self.profile.pk)
示例4: TestFlowEventViewSet
class TestFlowEventViewSet(TestCase):
def setUp(self):
self.view_set = views.FlowEventViewSet()
self.view_set.format_kwarg = ''
self.period = FlowEventFactory()
FlowEventFactory(timestamp=TIMEZONE.localize(datetime.datetime(2014, 2, 28)))
self.request = Request(HttpRequest())
self.request.__setattr__('user', self.period.user)
self.view_set.request = self.request
def test_list(self):
response = self.view_set.list(self.request)
self.assertEqual(1, len(response.data))
self.assertEqual(self.period.id, response.data[0]['id'])
def test_perform_create(self):
serializer = FlowEventSerializer(data={'timestamp': datetime.datetime(2015, 1, 1)})
serializer.is_valid()
self.view_set.perform_create(serializer)
self.assertEqual(self.request.user, serializer.instance.user)
示例5: test_multiple_shared_works
def test_multiple_shared_works(self):
request = RequestFactory().post(
'/',
HTTP_AUTHORIZATION='mkt-shared-secret '
'[email protected],56b6f1a3dd735d962c56'
'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
'9c68c31b3371aa8130317815c89e5072e31bb94b4'
'121c5c165f3515838d4d6c60c4,165d631d3c3045'
'458b4516242dad7ae')
drf_request = Request(request)
# Start with an AnonymousUser on the request, because that's a classic
# situation: we already went through a middleware, it didn't find a
# session cookie, if set request.user = AnonymousUser(), and now we
# are going through the authentication code in the API.
request.user = AnonymousUser()
drf_request.authenticators = (
authentication.RestSharedSecretAuthentication(),
authentication.RestOAuthAuthentication())
eq_(drf_request.user, self.profile.user)
eq_(drf_request._request.user, self.profile.user)
eq_(drf_request.user.is_authenticated(), True)
eq_(drf_request._request.user.is_authenticated(), True)
eq_(drf_request.amo_user.pk, self.profile.pk)
eq_(drf_request._request.amo_user.pk, self.profile.pk)
示例6: test_read_write_hyperlinked_collection_property
def test_read_write_hyperlinked_collection_property(self):
request = Request(make_dummy_request())
request._user = User(username='Patrick', is_superuser=True)
context = {'request': request}
serializer = ProjectSerializer(self.project, context=context)
field = serializer.get_fields()['notes']
property_serializer = HydraPropertySerializer(
field, 'notes',
'projectns:',
self.project,
context=context
)
supported_operations = property_serializer.data\
.get('property')\
.get('hydra:supportedOperation')
self.assertEqual(len(supported_operations), 2)
create_operation, = filter(lambda op: op.get('hydra:method') == 'POST',
supported_operations)
self.assertDictEqual(dict(create_operation), {
'@id': '_:project_note_create',
'@type': 'hydra:CreateResourceOperation',
'label': 'Create a note for this project.',
'description': None,
'hydra:method': 'POST',
'hydra:expects': 'projectns:Note',
'hydra:returns': 'projectns:Note',
'hydra:possibleStatus': []
})
示例7: test_collaborator_with_read_perms_can_delete_self
def test_collaborator_with_read_perms_can_delete_self(self):
"""
Tests that collaborator with read perms can only
delete it's own object.
"""
self.account_owner.is_owner = False
self.account_owner.save()
user = User.objects.create_user(
username='otheruser',
email='[email protected]',
password=self.password,
first_name='Other',
last_name='User'
)
self.board_collaborator.permission = 'read'
self.board_collaborator.user = user
self.board_collaborator.save()
request = Request(self.factory.delete('/', self.data, format='json'))
request.parsers = (JSONParser(), )
request.user = self.user
view = mock_view(request)
has_perm = self.perm_class.has_object_permission(
request, view, self.board_collaborator)
self.assertFalse(has_perm)
示例8: test_request_POST_with_form_content
def test_request_POST_with_form_content(self):
"""
Ensure request.POST returns content for POST request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.post('/', data))
request.parsers = (FormParser(), MultiPartParser())
assert list(request.POST.items()) == list(data.items())
示例9: test_request_POST_with_form_content
def test_request_POST_with_form_content(self):
"""
Ensure request.POST returns content for POST request with form content.
"""
data = {"qwerty": "uiop"}
request = Request(factory.post("/", data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.POST.items()), list(data.items()))
示例10: _make_api_call
def _make_api_call(self, requesting_user, target_user, course_key):
"""
Call the `course_detail` api endpoint to get information on the course
identified by `course_key`.
"""
request = Request(self.request_factory.get('/'))
request.user = requesting_user
return course_detail(request, target_user.username, course_key)
示例11: test_standard_behaviour_determines_form_content_PUT
def test_standard_behaviour_determines_form_content_PUT(self):
"""
Ensure request.DATA returns content for PUT request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.put('/', data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.DATA.items()), list(data.items()))
示例12: test_request_DATA_with_form_content
def test_request_DATA_with_form_content(self):
"""
Ensure request.DATA returns content for POST request with form content.
"""
data = {'qwerty': 'uiop'}
request = Request(factory.post('/', data))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.DATA.items()), list(data.items()))
示例13: _get_request
def _get_request(self, user=None):
"""
Build a Request object for the specified user.
"""
if user is None:
user = self.honor_user
request = Request(self.request_factory.get('/'))
request.user = user
return request
示例14: __make_sub_request
def __make_sub_request(request, url, resolver):
wsgi_request = copy(request._request)
wsgi_request.method = 'GET'
wsgi_request.path = wsgi_request.path_info = urlsplit(url).path
wsgi_request.resolver_match = resolver.resolve(wsgi_request.path_info)
sub_request = Request(wsgi_request)
sub_request.user = request.user
sub_request.authenticators = request.authenticators
return sub_request
示例15: test_request_POST_with_files
def test_request_POST_with_files(self):
"""
Ensure request.POST returns no content for POST request with file content.
"""
upload = SimpleUploadedFile("file.txt", b"file_content")
request = Request(factory.post('/', {'upload': upload}))
request.parsers = (FormParser(), MultiPartParser())
self.assertEqual(list(request.POST.keys()), [])
self.assertEqual(list(request.FILES.keys()), ['upload'])