Pull a form value from the request.

        .. note::

            The request stream will be read and left at EOF.
964411
def parse_form(self, req, name, field):
        
        form = self._cache.get("form")
        if form is None:
            self._cache["form"] = form = parse_form_body(req)
        return core.get_value(form, name, field)
1103529
def __stream_request(self, method, url, request_args, headers=None):
        
        headers = headers if headers else {}
        response = self.__request(method, url, request_args,
                                  headers=headers, stream=True)
        lines = response.iter_lines(ITER_LINES_CHUNKSIZE)
        for line in lines:
            if line:
                data = json.loads(line.decode("utf-8"))
                yield data
694441
def formvalue (form, key):
    """"""
    field = form.get(key)
    if isinstance(field, list):
        field = field[0]
    return field
849615
def post(self, request, **kwargs):
        
        forms = self.get_forms()
        if self.are_forms_valid(forms):
            return self.forms_valid(forms)
        else:
            return self.forms_invalid(forms)
1202142
def _get_input_validator(self, request):
        

        method = request.method.upper()
        if method != 'POST':
            return self.representation
        elif self.post_representation:
            return self.post_representation
        else:
            return self.representation
894007
def get(self, request, *args, **kwargs):
        
        #noinspection PyAttributeOutsideInit
        self.object_list    = self.get_queryset()
        context             = self.get_context_data(force_search=True)

        if self.form_class:
            context.update({'form': self.get_form()})

        if 'q' in request.GET or 'p' in request.GET:
            return render(
                request,
                '{0}/results.html'.format(self.template_dir),
                context
            )
        else:
            return render_modal_workflow(
                request,
                '{0}/chooser.html'.format(self.template_dir),
                '{0}/chooser.js'.format(self.template_dir),
                context
            )
200407
def _request(self, form, url=None, **kwargs):
        """"""
        method = str(form.get("method", "get"))
        action = form.get("action")
        url = urllib.parse.urljoin(url, action)
        if url is None:  # This happens when both `action` and `url` are None.
            raise ValueError('no URL to submit to')

        # read https://www.w3.org/TR/html52/sec-forms.html
        data = kwargs.pop("data", dict())
        files = kwargs.pop("files", dict())

        # Use a list of 2-tuples to better reflect the behavior of browser QSL.
        # Requests also retains order when encoding form data in 2-tuple lists.
        data = [(k, v) for k, v in data.items()]

        # Process form tags in the order that they appear on the page,
        # skipping those tags that do not have a name-attribute.
        selector = ",".join("{}[name]".format(i) for i in
                            ("input", "button", "textarea", "select"))
        for tag in form.select(selector):
            name = tag.get("name")  # name-attribute of tag

            # Skip disabled elements, since they should not be submitted.
            if tag.has_attr('disabled'):
                continue

            if tag.name == "input":
                if tag.get("type", "").lower() in ("radio", "checkbox"):
                    if "checked" not in tag.attrs:
                        continue
                    value = tag.get("value", "on")
                else:
                    # browsers use empty string for inputs with missing values
                    value = tag.get("value", "")

                if tag.get("type", "").lower() == "file":
                    # read http://www.cs.tut.fi/~jkorpela/forms/file.html
                    # in browsers, file upload only happens if the form
                    # (or submit button) enctype attribute is set to
                    # "multipart/form-data". We don't care, simplify.
                    filename = value
                    if filename != "" and isinstance(filename, string_types):
                        content = open(filename, "rb")
                    else:
                        content = ""
                    # If value is the empty string, we still pass it for
                    # consistency with browsers (see #250).
                    files[name] = (filename, content)
                else:
                    data.append((name, value))

            elif tag.name == "button":
                if tag.get("type", "").lower() in ("button", "reset"):
                    continue
                else:
                    data.append((name, tag.get("value", "")))

            elif tag.name == "textarea":
                data.append((name, tag.text))

            elif tag.name == "select":
                # If the value attribute is not specified, the content will
                # be passed as a value instead.
                options = tag.select("option")
                selected_values = [i.get("value", i.text) for i in options
                                   if "selected" in i.attrs]
                if "multiple" in tag.attrs:
                    for value in selected_values:
                        data.append((name, value))
                elif selected_values:
                    # A standard select element only allows one option to be
                    # selected, but browsers pick last if somehow multiple.
                    data.append((name, selected_values[-1]))
                elif options:
                    # Selects the first option if none are selected
                    first_value = options[0].get("value", options[0].text)
                    data.append((name, first_value))

        if method.lower() == "get":
            kwargs["params"] = data
        else:
            kwargs["data"] = data

        return self.session.request(method, url, files=files, **kwargs)
65496
private String getFormDataId(HttpServletRequest request) {

        String result = request.getParameter(CmsUgcConstants.PARAM_FORM_DATA_ID);
        return result;
    }
264869
private void parseValue() {
        ChannelBuffer content = this.request.getContent();
        this.parsedValue = new byte[content.capacity()];
        content.readBytes(parsedValue);
    }
224146
def _receive_eol_token(self):
        
        while self.EOL_TOKEN is None:
            # use yield to have data sent to us - store in buffer
            self._buffer += yield
            if len(self._buffer) > MAX_REQUEST_LENGTH:
                raise HTTPErrorBadRequest("Max request length exceeded")
            self.EOL_TOKEN = self.determine_newline(self._buffer)
883814
def read_request_from_str(data, **params):
    
    method, uri = None, None
    headers = {}
    host = ''

    try:
        split_list = data.split('\n\n')
        headers_text = split_list[0]
        body = '\n\n'.join(split_list[1:])
    except:
        headers_text = data
        body = ''

    body = force_bytes(body)
    for k, v in params.items():
        body = body.replace(b'{%s}' % force_bytes(k), force_bytes(v))

    header_list = headers_text.split('\n')

    for i, line in enumerate(header_list):
        line = line.strip()
        if line.strip() == '':
            continue

        line = line.format(**params)
        if i == 0:
            # 至多3个
            split_line = line.strip().split(' ')
            method, uri, _ = split_line[0], ' '.join(split_line[1:-1]), split_line[-1]
        else:
            # 至多2个
            header, value = line.split(':', 1)
            header = header.strip()
            value = value.strip()
            headers[header] = value
            if header.lower() == 'host':
                host = value

    return headers, method, uri, host, body
172182
def request( self, url, method='get',
			decode=None, encode=None, data=None,
			headers=None, raise_for=dict(), queue_lines=None ):
		''''''
		if self.debug_requests:
			url_debug = _dump_trunc(url)
			log.debug('HTTP request: {} {} (h: {}, enc: {}, dec: {}, data: {!r})'.format(
				method, url_debug, headers, encode, decode, _dump_trunc(data) ))

		timeout = HTTPTimeout(**self.request_io_timeouts)
		req_headers = {'User-Agent': 'txU1'}

		if data is not None:
			if encode == 'files':
				boundary = os.urandom(16).encode('hex')
				req_headers['Content-Type'] = 'multipart/form-data; boundary={}'.format(boundary)
				data = MultipartDataSender(data, boundary)
				if not callable(headers): yield data.calculate_length()
				else:
					body = io.BytesIO()
					yield data.calculate_length(body)
					headers = headers(url, method, body.getvalue(), 'multipart/form-data')
			else:
				if encode is None:
					if isinstance(data, types.StringTypes): data = io.BytesIO(data)
				elif encode == 'form':
					req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
					data = io.BytesIO(urllib.urlencode(data))
				elif encode == 'json':
					req_headers['Content-Type'] = 'application/json'
					data = io.BytesIO(json.dumps(data))
				else: raise ValueError('Unknown request encoding: {}'.format(encode))
				if callable(headers):
					data.seek(0)
					headers = headers(url, method, data.read(), req_headers.get('Content-Type'))
				data = FileBodyProducer(data)
		elif callable(headers): headers = headers(url, method, '', None)

		# Passed "headers" should be allowed to be modified by body_hash()
		for k, v in (headers or dict()).viewitems():
			req_headers[force_bytes(k)] = force_bytes(v)
		url, method = it.imap(force_bytes, [url, method.lower()])

		if decode == 'json': req_headers.setdefault('Accept', 'application/json')
		elif decode is not None:
			raise ValueError('Unknown response decoding method: {}'.format(decode))

		res_deferred = first_result( timeout,
			self.request_agent.request( method.upper(), url,
				Headers(dict((k,[v]) for k,v in req_headers.viewitems())), data ) )
		code = res_body = None
		try:
			res = yield res_deferred
			code = res.code
			if code == http.NO_CONTENT: defer.returnValue(None)
			if code not in [http.OK, http.CREATED]:
				if self.debug_requests:
					res_body = defer.Deferred()
					res.deliverBody(DataReceiver(res_body, timer=timeout, allow_loss=True))
					res_body = yield first_result(timeout, res_body)
					log.debug('HTTP error response body: {!r}'.format(res_body))
				raise ProtocolError(code, res.phrase)

			res_body = defer.Deferred()
			res.deliverBody(DataReceiver(res_body, timer=timeout))
			res_body = yield first_result(timeout, res_body)

			if self.debug_requests:
				log.debug( 'HTTP request done ({} {}): {} {} {}, body_len: {}'\
					.format(method, url_debug, code, res.phrase, res.version, len(res_body)) )
			defer.returnValue(json.loads(res_body) if decode is not None else res_body)

		except ( timeout.ActivityTimeout, TimeoutError,
				ResponseFailed, RequestNotSent, RequestTransmissionFailed ) as err:
			if isinstance(err, timeout.ActivityTimeout):
				if not res_deferred.called: res_deferred.cancel()
				if res_body and not res_body.called: res_body.cancel()
			if self.debug_requests:
				log.debug(
					'HTTP transport (underlying protocol) error ({} {}): {}'\
					.format(method, url_debug, err.message or repr(err.args)) )
			raise UnderlyingProtocolError(err)

		except ProtocolError as err:
			if self.debug_requests:
				log.debug(
					'HTTP request handling error ({} {}, code: {}): {}'\
					.format(method, url_debug, code, err.message) )
			raise raise_for.get(code, ProtocolError)(code, err.message)

		except RequestGenerationFailed as err:
			err[0][0].raiseException()

		finally: timeout.state_finished()
389174
def _request(self, uri, params=None, postParams=None, verb='GET'):
        """"""
        return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True)
205000
def __get_value(self, field_name):
        
        value = request.values.get(field_name)
        if value is None:
            if self.json_form_data is None:
                value = None
            elif field_name in self.json_form_data:
                value = self.json_form_data[field_name]
        return value
796857
def read(self):
		
		self.repr_.setvalue(ord(self.open_stream_in.read(1)))
		return self.value.getvalue()
1108693
async def _process_2auth_form(self, html: str) -> (str, str):
        
        # Parse page
        p = TwoFactorCodePageParser()
        p.feed(html)
        p.close()

        # Prepare request data
        form_url = p.url
        form_data = dict(p.inputs)
        form_data['remember'] = 0
        if p.message:
            raise VkAuthError('invalid_data', p.message, form_url, form_data)
        form_data['code'] = await self.enter_confirmation_code()

        # Send request
        url, html = await self.driver.post_text(form_url, form_data)
        return url, html
1314649
def parse_request(self, request, parameters=None, fake_method=None):
        '''
        
        '''
        return (request.method,
                request.url,
                request.headers,
                request.form.copy())