当前位置: 首页>>代码示例>>Python>>正文


Python HttpRequest.POST方法代码示例

本文整理汇总了Python中django.http.HttpRequest.POST方法的典型用法代码示例。如果您正苦于以下问题:Python HttpRequest.POST方法的具体用法?Python HttpRequest.POST怎么用?Python HttpRequest.POST使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.http.HttpRequest的用法示例。


在下文中一共展示了HttpRequest.POST方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_workflow_03

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
    def test_workflow_03(self):
        msgt('(3) Try with HttpRequest - POST')
        
        msg('(a) Try form with HttpRequest object')
        h = HttpRequest()
        h.POST = self.expected_params
        
        f1 = CheckForExistingLayerForm(h.POST)
        self.assertEqual(f1.is_valid(), True)
        
        msg('(b) Try signature validity check - break assertion by sending dict, not HttpRequest')
        self.assertRaises(AssertionError, f1.is_signature_valid_check_post, h.POST)
            
            
        msg('(c) Try signature check with invalid data--no signature key')
        h_bad_data = HttpRequest()
        h_bad_data.POST = self.test_data 
        self.assertEqual(f1.is_signature_valid_check_post(h_bad_data), False)

        msg('(d) Try signature check with invalid data--bad signature key')
        h_bad_data2 = HttpRequest()
        h_bad_data2.POST = self.expected_params_bad_signature
        self.assertEqual(f1.is_signature_valid_check_post(h_bad_data2), False)

        msg('(e) Try signature check with valid data')
        self.assertEqual(f1.is_signature_valid_check_post(h), True)
        
        msg('(f) cleaned data.')
        self.assertEqual(f1.cleaned_data, self.expected_clean_data)
开发者ID:IQSS,项目名称:shared-dataverse-information,代码行数:31,代码来源:test_form_existing_layer.py

示例2: _wrapped_view_func

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
    def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
        # Adapted from django/http/__init__.py.
        # So by default Django doesn't populate request.POST for anything besides
        # POST requests. We want this dict populated for PATCH/PUT, so we have to
        # do it ourselves.
        #
        # This will not be required in the future, a bug will be filed against
        # Django upstream.

        if not request.POST:
            # Only take action if POST is empty.
            if request.META.get('CONTENT_TYPE', '').startswith('multipart'):
                # Note that request._files is just the private attribute that backs the
                # FILES property, so we are essentially setting request.FILES here.  (In
                # Django 1.5 FILES was still a read-only property.)
                request.POST, request._files = MultiPartParser(
                    request.META,
                    BytesIO(request.body),
                    request.upload_handlers,
                    request.encoding
                ).parse()
            else:
                request.POST = QueryDict(request.body, encoding=request.encoding)

        return view_func(request, *args, **kwargs)
开发者ID:brainwane,项目名称:zulip,代码行数:27,代码来源:decorator.py

示例3: test_POST_then_GET

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
 def test_POST_then_GET(self):
     request_POST = HttpRequest()
     request_POST.method = 'POST'
     request_POST.POST = {const.KEY_ID: "",
                          const.KEY_SOURCE: "[email protected]",
                          const.KEY_DEST: "[email protected]",
                          const.KEY_CONTENT: "text content",
                          const.KEY_READY_TIME: "2000-09-13T04:22:58.100Z"}
     response_POST = taskrouter(request=request_POST,
                                owner_key=self.taskowner.key,
                                task_id=None)
     json_POST = json.loads(response_POST.content)
     task_id = json_POST[const.KEY_ID]
     
     request_GET = HttpRequest()
     request_GET.method = 'GET'
     response_GET = taskrouter(request=request_GET,
                               owner_key=self.taskowner.key,
                               task_id=task_id)
     json_GET = json.loads(response_GET.content)
     
     self.assertEqual(json_GET[const.KEY_ID], task_id)
     self.assertEqual(json_GET[const.KEY_SOURCE], request_POST.POST[const.KEY_SOURCE])
     self.assertEqual(json_GET[const.KEY_DEST], request_POST.POST[const.KEY_DEST])
     self.assertEqual(json_GET[const.KEY_CONTENT], request_POST.POST[const.KEY_CONTENT])
     self.assertEqual(json_GET[const.KEY_READY_TIME], request_POST.POST[const.KEY_READY_TIME])
开发者ID:jzerbe,项目名称:taskifier,代码行数:28,代码来源:full.py

示例4: testFileUpload

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
    def testFileUpload(self):
        from django.http import QueryDict, HttpRequest
        from tardis.tardis_portal.views import upload
        from django.core.files import File
        from django.core.files.uploadedfile import UploadedFile
        from django.utils.datastructures import MultiValueDict
        from os import path

        # create request.FILES object

        django_file = File(self.f1)
        uploaded_file = UploadedFile(file=django_file)
        uploaded_file.name = self.filename
        uploaded_file.size = self.f1_size

        post_data = [("enctype", "multipart/form-data")]
        post = QueryDict("&".join(["%s=%s" % (k, v) for (k, v) in post_data]))

        files = MultiValueDict({"Filedata": [uploaded_file]})
        request = HttpRequest()
        request.FILES = files
        request.POST = post
        request.method = "POST"
        response = upload(request, self.dataset.id)
        test_files_db = models.Dataset_File.objects.filter(dataset__id=self.dataset.id)

        self.assertTrue(path.exists(path.join(self.dataset_path, self.filename)))
        self.assertTrue(self.dataset.id == 1)
        self.assertTrue(test_files_db[0].url == "tardis://testfile.txt")
开发者ID:aaryani,项目名称:CoreTardisTemp,代码行数:31,代码来源:test_views.py

示例5: decode_request

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
def decode_request(value):
    """
    Decodes a request JSONish value to a HttpRequest object.
    """
    request = HttpRequest()
    request.GET = CustomQueryDict(value['get'])
    request.POST = CustomQueryDict(value['post'])
    request.COOKIES = value['cookies']
    request.path = value['path']
    request.method = value['method']
    request.reply_channel = value['reply_channel']
    # Channels requests are more high-level than the dumping ground that is
    # META; re-combine back into it
    request.META = {
        "REQUEST_METHOD": value["method"],
        "SERVER_NAME": value["server"][0],
        "SERVER_PORT": value["server"][1],
        "REMOTE_ADDR": value["client"][0],
        "REMOTE_HOST": value["client"][0],  # Not the DNS name, hopefully fine.
    }
    for header, header_value in value.get("headers", {}).items():
        request.META["HTTP_%s" % header.upper()] = header_value
    # We don't support non-/ script roots
    request.path_info = value['path']
    return request
开发者ID:ydaniv,项目名称:channels,代码行数:27,代码来源:request.py

示例6: test_post_create_form_is_valid_and_response_redirects

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
	def test_post_create_form_is_valid_and_response_redirects(self):
		request = HttpRequest()
		request.POST = QueryDict('title=NewTitle&content=NewContent')
		response = post_create(request)
		self.assertEqual(1, Post.objects.count())
		self.assertEqual(302, response.status_code)
		self.assertEqual(self.post.get_details_url(), response.url)
开发者ID:khardi,项目名称:demo_blog,代码行数:9,代码来源:tests.py

示例7: add_a_new_course_through_request

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
def add_a_new_course_through_request(
        id,
        name,
        college,
        classroom,
        score,
        max_student_number,
        remark,
        teacher=[],
        time=[],
        exam=None,
):
    request = HttpRequest()
    request.method = 'POST'
    request.POST = {
        'id'                 : id,
        'name'               : name,
        'college'            : college,
        'classroom'          : classroom,
        'score'              : score,
        'max_student_number' : max_student_number,
        'remark'             : remark,
        'teacher'            : teacher,
        'time'               : time,
        'exam'               : exam,
    }
    response = add_course(request)
    return response
开发者ID:dsdshcym,项目名称:course-pick,代码行数:30,代码来源:tests.py

示例8: test_uploadCSVToProcess

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
 def test_uploadCSVToProcess(self):
     request = HttpRequest()
     request.method = 'POST'
     request.POST = "test"
     request.FILES = {'name':File(open('tests/data/GSM999999999.TXT','rb'))}
     request.upload_handlers
     views.uploadCSVToProcess(request)
开发者ID:NCSU-VSR,项目名称:wolfscout,代码行数:9,代码来源:tests.py

示例9: test_login_csrf_rotate

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
    def test_login_csrf_rotate(self, password='password'):
        """
        Makes sure that a login rotates the currently-used CSRF token.
        """
        # Do a GET to establish a CSRF token
        # TestClient isn't used here as we're testing middleware, essentially.
        req = HttpRequest()
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        # get_token() triggers CSRF token inclusion in the response
        get_token(req)
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token1 = csrf_cookie.coded_value

        # Prepare the POST request
        req = HttpRequest()
        req.COOKIES[settings.CSRF_COOKIE_NAME] = token1
        req.method = "POST"
        req.POST = {'username': 'testclient', 'password': password, 'csrfmiddlewaretoken': token1}

        # Use POST request to log in
        SessionMiddleware().process_request(req)
        CsrfViewMiddleware().process_view(req, login_view, (), {})
        req.META["SERVER_NAME"] = "testserver"  # Required to have redirect work in login view
        req.META["SERVER_PORT"] = 80
        resp = login_view(req)
        resp2 = CsrfViewMiddleware().process_response(req, resp)
        csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None)
        token2 = csrf_cookie.coded_value

        # Check the CSRF token switched
        self.assertNotEqual(token1, token2)
开发者ID:dakusan,项目名称:django,代码行数:35,代码来源:test_views.py

示例10: nodeWrapper

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
def nodeWrapper(smiles, height, width, scale, key=None):
	"""
	Wraps image html tag around
	the molecule's image source
	Inputs: smiles, height, width, scale, key
	Returns: html of wrapped image
	"""

	# 1. Get image from smiles
	post = {
		"smiles": smiles,
		"scale": scale,
		"height": height,
		"width": width
	}
	request = HttpRequest()
	request.POST = post
	results = jchem_rest.smilesToImage(request)

	# 2. Get imageUrl out of results
	data = json.loads(results.content) # json string --> dict
	img, imgScale = '', ''
	if 'data' in data:
		root = data['data'][0]['image']
		if 'image' in root:
			img = root['image']

	# 3. Wrap imageUrl with <img>
	html = imgTmpl().render(Context(dict(smiles=smiles, img=img, height=height, width=width, scale=scale, key=key)))	
	return html
开发者ID:pavgup,项目名称:ubertool_cts,代码行数:32,代码来源:data_walks.py

示例11: start_two_factor_auth

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
def start_two_factor_auth(request: HttpRequest,
                          extra_context: ExtraContext=None,
                          **kwargs: Any) -> HttpResponse:
    two_fa_form_field = 'two_factor_login_view-current_step'
    if two_fa_form_field not in request.POST:
        # Here we inject the 2FA step in the request context if it's missing to
        # force the user to go to the first step of 2FA authentication process.
        # This seems a bit hackish but simplifies things from testing point of
        # view. I don't think this can result in anything bad because all the
        # authentication logic runs after the auth step.
        #
        # If we don't do this, we will have to modify a lot of auth tests to
        # insert this variable in the request.
        request.POST = request.POST.copy()
        request.POST.update({two_fa_form_field: 'auth'})

    """
    This is how Django implements as_view(), so extra_context will be passed
    to the __init__ method of TwoFactorLoginView.

    def as_view(cls, **initkwargs):
        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            ...

        return view
    """
    two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context,
                                             **kwargs)
    return two_fa_view(request, **kwargs)
开发者ID:akashnimare,项目名称:zulip,代码行数:32,代码来源:auth.py

示例12: test

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
 def test(self):
     Vendor.objects.create(pk=256)
     disc = Disc.objects.create(status='default')
     prix = Prix.objects.create(code='PCFA')
     request = HttpRequest()
     request.method= 'POST'
     query_dict = QueryDict('batchpath=%s' % (self.tmp_batch_path)).copy()
     query_dict.update({'label-0-release_title_hidden' : u"N'ayons pas peur! - Hommage \xe0 l'homme de paix",
                        'release-0-pk' : u'1591',
                        'release-0-artist_name_hidden' : u'Varioust Artists',
                        'label-0-mdx_label_id': u'2345',
                        'release-TOTAL_FORMS' : u'1',
                        'label-0-name_hidden' : u'Ad Vitam records',
                        'label-INITIAL_FORMS' : u'1',
                        'release-INITIAL_FORMS': u'1',
                        'release-0-label_name_hidden': u'Ad Vitam records',
                        'label-0-name_auto' : u'AD VITAM Records',
                        'label-TOTAL_FORMS': u'1',
                        'label-0-pk': u'84', 
                        'artist-TOTAL_FORMS': u'0',
                        'label-0-create': u'1',
                        'release-0-title_hidden': u"N'ayons pas peur! - Hommage \xe0 l'homme de paix",
                        'artist-INITIAL_FORMS': u'0'
                        })
     request.POST = query_dict
     batch_process = BatchProcessor(request)
     batch_process.process()
     album = Album.objects.get()
     artist = Artist.objects.get()
     self.assertEqual('compilation', artist.type)
开发者ID:cazino,项目名称:Ingestion,代码行数:32,代码来源:viewtest.py

示例13: test_save_content

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
 def test_save_content(self):
     """ Test the save_content() view. """
     data = {'key': 'my_key', 'content': 'my content', 'onlick': 'rabbits()'}
     mock_api = EditModeNoOpAPI()
     request = HttpRequest()
     request.method = 'POST'
     request.POST = data
     #Test that in a 'normal' situation our view calls the api's save_content_data
     #method and returns a 200 response
     with mock.patch.object(mock_api, "save_content_data") as mock_api_save_data:
         with mock.patch("contentious.views.api", new=mock_api):
             with mock.patch("contentious.decorators.api", new=mock_api):
                 response = save_content_view(request)
         self.assertEqual(response.status_code, 200)
         self.assertEqual(mock_api_save_data.call_count, 1)
         expected_data_for_save = data.copy()
         expected_key_for_save = expected_data_for_save.pop('key') #cunning
         self.assertEqual( mock_api_save_data.call_args[0][0], expected_key_for_save)
         self.assertEqual( mock_api_save_data.call_args[0][1], expected_data_for_save)
     #Test that if the api raises a ValidationError that the view function returns a
     #JSON response containing the errors dict
     error_dict = {'onlick': 'Sorry, rabbits() is not valid.'}
     def raise_error(*args, **kwargs):
         """ Mock for the save_content_data method of the api. """
         raise ValidationError(error_dict)
     with mock.patch.object(mock_api, "save_content_data", new=raise_error):
         with mock.patch("contentious.views.api", new=mock_api):
             with mock.patch("contentious.decorators.api", new=mock_api):
                 response = save_content_view(request)
     self.assertEqual(response.status_code, 400)
     self.assertEqual(json.loads(response.content), error_dict)
开发者ID:pablorecio,项目名称:contentious,代码行数:33,代码来源:views.py

示例14: test_httprequest_repr

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
 def test_httprequest_repr(self):
     request = HttpRequest()
     request.path = "/somepath/"
     request.GET = {"get-key": "get-value"}
     request.POST = {"post-key": "post-value"}
     request.COOKIES = {"post-key": "post-value"}
     request.META = {"post-key": "post-value"}
     self.assertEqual(
         repr(request),
         str_prefix(
             "<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"
         ),
     )
     self.assertEqual(build_request_repr(request), repr(request))
     self.assertEqual(
         build_request_repr(
             request,
             path_override="/otherpath/",
             GET_override={"a": "b"},
             POST_override={"c": "d"},
             COOKIES_override={"e": "f"},
             META_override={"g": "h"},
         ),
         str_prefix(
             "<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"
         ),
     )
开发者ID:hellhovnd,项目名称:django,代码行数:29,代码来源:tests.py

示例15: gen_test_report

# 需要导入模块: from django.http import HttpRequest [as 别名]
# 或者: from django.http.HttpRequest import POST [as 别名]
def gen_test_report(the_user, gen_number=10, job_duration=30, time_break=1):
	from breeze.views import report_overview
	import time

	posted = dict()
	posted["project"] = 1
	posted["Section_dbID_9"] = 0
	posted["9_opened"] = 'False'
	posted["Dropdown"] = 'Enter'
	posted["Textarea"] = ''
	posted["Section_dbID_81"] = 0
	posted["81_opened"] = 'False'
	posted["Section_dbID_118"] = '1'
	posted["118_opened"] = 'True'
	posted["sleep duration"] = str(job_duration)
	posted["sleep_duration"] = str(job_duration)
	posted["wait_time"] = str(job_duration)
	posted["Groups"] = ''
	posted["Individuals"] = ''

	rq = HttpRequest()
	# del rq.POST
	rq.POST = posted
	rq.user = the_user
	rq.method = 'POST'

	for i in range(1, gen_number + 1):
		name = 'SelfTest%s' % i
		print name
		report_overview(rq, 'TestPipe', name, '00000')
		time.sleep(time_break)

	print 'done.'
开发者ID:findcomrade,项目名称:isbio,代码行数:35,代码来源:system_check.py


注:本文中的django.http.HttpRequest.POST方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。