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


Python Request.data方法代码示例

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


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

示例1: urlopen

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def urlopen(self, url, param=None, data=None, headers={}, proxies={}, timeout=None, encoding='utf8', errors='strict'):
        """ 打开目标链接, 返回一个 HttpResponse对象.

        @url(str/Request): 目标链接.
        @param(str/dict/pairs tuple): query string.
        @data(bytes/str/dict): post data.
        @headers(dict): http request headers.
        @proxies(dict): 代理, 如:{'http': 'xx.xx.xx.xx:3128', 'https': 'xxx.xxx.xxx.xxx:8080'}.
        @timeout(int): http request timeout.
        @encoding/errors(str): url编码.
        """
        if param:
            full_url = isinstance(url, Request) and url.get_full_url() or url
            url_parse_dict = urlparse(full_url)._asdict()
            query_param = url_parse_dict.get('query') + (isinstance(param, str) and param or urlencode(param, encoding, errors))
            url_parse_dict['query'] = query_param
            full_url = urlunparse(url_parse_dict.values())
            request = Request(full_url)
        else:
            request = isinstance(url, Request) and url or Request(url)
        if data:
            if isinstance(data, bytes):
                request.data = data
            elif isinstance(data, str):
                request.data = data.encode(encoding, errors)
            else:
                request.data = urlencode(data).encode(encoding, errors)
        for key, value in headers.items():
            request.add_header(key, value)
        for proxy_type, proxy_host in proxies.items():
            request.set_proxy(proxy_host, proxy_type)
        self.last_request = request
        self.last_response = self.opener.open(request, timeout=timeout)
        return self.last_response
开发者ID:mrwlwan,项目名称:workspace2014,代码行数:36,代码来源:kisopener.py

示例2: upload

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def upload(self):
        ###Everything about uploding data to GeoServer is handling in here.
        status = 1  # I use it for managing operations. If status = 0 nothing to do.
        if not self.upDlg.urlText.text() or not self.upDlg.userText.text() \
                or not self.upDlg.passText.text() or not self.upDlg.sldText.text():
            QMessageBox.critical(None, 'Information', 'Please fill in all fields.')

        else:
            username = self.upDlg.userText.text()
            password = self.upDlg.passText.text()
            sldName = self.upDlg.sldText.text()
            login = base64.b64encode(str.encode(username + ':' + password)).decode("utf-8")
            basicLogin = 'Basic ' + login  # Base64 auth for REST service.

            # Deleting the SLD if exists on GeoServer.
            if self.upDlg.urlText.text()[-1] == '/':
                usableUrl = self.upDlg.urlText.text()[:len(
                    self.upDlg.urlText.text()) - 1]  # Maybe user add slash '/' in the end of url, so this problem is solved in this way.
            else:  # I didnt use urlparse lib. Because this solution is simplier than it.
                usableUrl = self.upDlg.urlText.text()

            try:
                url = usableUrl + '/styles/' + sldName + ".sld"
                requestPut = Request(url)
                requestPut.add_header("Authorization", basicLogin)
                requestPut.add_header("Content-type", "application/vnd.ogc.sld+xml")
                requestPut.add_header("Accept", "*/*")
                requestPut.data = str.encode(self.dlg.sldText1.text())
                requestPut.get_method = lambda: 'PUT'
                urlopen(requestPut)
                QMessageBox.information(None, 'Information', 'The style was succesfully uploaded.')
                self.upDlg.close()
            except:
                try:
                    url = usableUrl + '/styles'
                    requestPrepare = Request(url)
                    requestPrepare.add_header("Authorization", basicLogin)
                    requestPrepare.add_header("Content-type", "text/xml")
                    requestPrepare.add_header("Accept", "*/*")
                    requestPrepare.data = str.encode(
                        '<style><name>' + sldName + '</name><filename>' + (sldName + '.sld') + '</filename></style>')  #

                    urlopen(requestPrepare)

                    url = usableUrl + '/styles/' + sldName + ".sld"
                    requestPut = Request(url)
                    requestPut.add_header("Authorization", basicLogin)
                    requestPut.add_header("Content-type", "application/vnd.ogc.sld+xml")
                    requestPut.add_header("Accept", "*/*")
                    requestPut.data = str.encode(self.dlg.sldText1.text())
                    requestPut.get_method = lambda: 'PUT'
                    urlopen(requestPut)
                    QMessageBox.information(None, 'Information', 'The style was succesfully uploaded.')
                    self.upDlg.close()
                except Exception as error:
                    QMessageBox.critical(None, 'Information', str(error))
开发者ID:MSBilgin,项目名称:SLD4raster,代码行数:58,代码来源:sld4raster.py

示例3: _CallHttp

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def _CallHttp(self, method, handler, data=''):
        method = method.upper()
        request_uri = self._BuildUri(handler)
        req = Request(request_uri, method=method)
        if isinstance(data, collections.Mapping):
            req.add_header('content-type', 'application/json')
            data = json.dumps(data, ensure_ascii=False)
        data = data.encode('utf-8')
        hmac = self._HmacForRequest(method,
                                    urlparse(request_uri).path,
                                    data)
        req.add_header(HMAC_HEADER, hmac)
        req.data = data
        try:
            resp = urlopen(req)
        except HTTPError as err:
            readData = err.read().decode('utf-8')
            print('[C++YouCompleteMe] Error from ycmd server: {}'.format(
                json.loads(readData).get('message', '')))
            return ''

        readData = resp.read()
        # self._ValidateResponseObject(
            # readData, resp.getheader(HMAC_HEADER).encode('utf-8'))

        return readData.decode('utf-8')
开发者ID:imaveek,项目名称:CppYCM,代码行数:28,代码来源:ycmd_handler.py

示例4: uploadFile

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
def uploadFile(opener, address, fileName, fileContents, mimeType, data):
    boundary = encode64(urandom(32))
    fileName = fileName.encode("utf-8")
    contentType = b'multipart/form-data; boundary=' + boundary
    partBoundary = b"--" + boundary
    formContents = []
    formContents.extend([b'',
                         partBoundary,
                         b'Content-Disposition: form-data; name="' + POST_UPLOADED_FILE.encode(
                             "ascii") + b'"; filename="' + fileName + b'"',
                         b'Content-Type: ' + mimeType,
                         b'',
                         fileContents,
                         partBoundary
    ])
    for key in data:
        addedParams = [b'Content-Disposition: form-data; name="' + key.encode("utf-8") + b'"',
                       b'',
                       data[key].encode("ascii"),
                       partBoundary
                       ]
        formContents.extend(addedParams)
    formContents[-1] = b"--"+boundary+b"--"
    requestBody = b"\r\n".join(formContents)
    try:
        request = Request(address)
        request.add_header('Content-type', contentType)
        request.add_header('Content-length', len(requestBody))
        request.data = requestBody
        response = opener.open(request).read()
    except OSError:
        response = RESPONSE_NETWORK_ERROR
    if response in errorResponses:
        raise SecureMessagingException(response)
    return response
开发者ID:nidzo732,项目名称:SecureMessaging,代码行数:37,代码来源:HTTPStuff.py

示例5: _CallHttp

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def _CallHttp(self, method, handler, data=''):
        method = method.upper()
        req = Request(self._BuildUri(handler), method=method)
        if isinstance(data, collections.Mapping):
            req.add_header('content-type', 'application/json')
            data = json.dumps(data, ensure_ascii=False)
        data = data.encode('utf-8')
        request_hmac = self._HmacForBody(b''.join([
            self._HmacForBody(method.encode('utf-8')),
            self._HmacForBody(urljoin('/', handler).encode('utf-8')),
            self._HmacForBody(data),
        ]), to_base64=True)
        req.add_header(HMAC_HEADER, request_hmac)

        req.data = data
        try:
            resp = self.proxyLessUrlOpen.open(req)
        except HTTPError as err:
            print('[Cppinabox] HTTP Error ' + str( err.code ) )
            try:
                readData = err.read().decode('utf-8')
                print('                   Error from ycmd server: {}'.format(
                    json.loads(readData).get('message', '')))
            except:
                pass
                    
            return ''

        readData = resp.read()
        self._ValidateResponseObject(
            readData, resp.getheader(HMAC_HEADER).encode('utf-8'))

        return readData.decode('utf-8')
开发者ID:kracejic,项目名称:cppinabox,代码行数:35,代码来源:ycm_handler.py

示例6: __open

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
	def __open(self, url, headers={}, data=None, baseurl=""):
		"""Raw urlopen command"""
		if not baseurl:
			baseurl = self.baseurl
		req = Request("%s%s" % (baseurl, url), headers=headers)
		try:
			req.data = urlencode(data).encode('utf-8') # Python 3
		except:
			try:
				req.add_data(urlencode(data)) # Python 2
			except:
				pass

		# Proxy support
		if self.proxy_url is not None:
			if self.proxy_user is None:
				handler = ProxyHandler({'https': self.proxy_url})
				opener = build_opener(handler)
			else:
				proxy = ProxyHandler({'https': 'https://%s:%[email protected]%s' % (self.proxy_user,
																	 self.proxy_password, self.proxy_url)})
				auth = HTTPBasicAuthHandler()
				opener = build_opener(proxy, auth, HTTPHandler)
			resp = opener.open(req)
		else:
			resp = urlopen(req)
		charset = resp.info().get('charset', 'utf-8')
		return json.loads(resp.read().decode(charset))
开发者ID:the-mace,项目名称:teslajson,代码行数:30,代码来源:teslajson.py

示例7: call_rpc

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
def call_rpc(method=None, arguments=None):
    global session_id

    request = Request(rpc_url)

    if session_id:
        request.add_header(SESSION_ID_HEADER_NAME, session_id)

    if method:
        payload = {'method': method}
        if arguments:
            payload['arguments'] = arguments
        json_data = json.dumps(payload)
        request.data = json_data.encode('utf-8')

    response = None

    try:
        response = urlopen(request)
    except HTTPError as e:
        # The first request will return a 409 status that includes a session id
        # we need to include in the header of all subsequent requests. So get it
        # from the 409 response and save it.
        if e.code == 409:
            session_id = e.headers[SESSION_ID_HEADER_NAME]
            response = call_rpc(method, arguments)
        else:
            sys.exit('Got an unexpected response from RPC: {0} {1}, aborting.'.format(e.code, e.message))
    except URLError as e:
        sys.exit('Could not connect to Transmission. Is it running and allows remote access? {0}'.format(e.reason))

    return response
开发者ID:alvaray,项目名称:torrent,代码行数:34,代码来源:transmission_announce_edit.py

示例8: test_can_post_data

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
 def test_can_post_data(self):
     cas_base = 'https://example.com'
     url = 'https://example.com/abc'
     headers = {
         'soapaction': 'http://www.oasis-open.org/committees/security',
         'cache-control': 'no-cache',
         'pragma': 'no-cache',
         'accept': 'text/xml',
         'connection': 'keep-alive',
         'content-type': 'text/xml'
     }
     params = {'TARGET': url}
     uri = '{}cas/samlValidate?{}'.format(cas_base, urlencode(params))
     request = Request(uri, '', headers)
     request.data = get_saml_assertion('ticket')
     try:
         urlopen(request)
     except URLError:
         # As long as this isn't a TypeError, and the url request
         # was actually made, then we can assert that
         # get_saml_assertion() is good. This is to prevent an
         # issue introduced since Python 3:
         #
         #  POST data should be bytes or an iterable of bytes. It
         #  cannot be of type str.
         #
         pass
开发者ID:ccnmtl,项目名称:djangowind,代码行数:29,代码来源:test_auth.py

示例9: getUsers

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def getUsers(self, users):
        req = Request("https://api.twitter.com/1.1/users/lookup.json")
        req.method = "POST"
        req.data = urllib.parse.urlencode({"screen_name": ",".join(users)}).encode()
        req.add_header("Authorization", "Bearer {}".format(self.bearerToken))
        req.add_header("Content-type", "application/x-www-form-urlencoded")

        with urlopen(req) as resp:
            return json.loads(resp.read().decode())
开发者ID:poke,项目名称:twitter-avatar-fetcher,代码行数:11,代码来源:avatar-fetcher.py

示例10: _CallHttp

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
 def _CallHttp(self, method, handler, data=None):
     method = method.upper()
     req = Request(self._BuildUri(handler), method=method)
     if isinstance(data, collections.Mapping):
         req.add_header("content-type", "application/json")
         data = ToUtf8Json(data)
     req.add_header(HMAC_HEADER, self._HmacForRequest(method, handler, data))
     req.data = bytes(data, "utf-8")
     readData = urlopen(req).read().decode("utf-8")
     return readData
开发者ID:rokn,项目名称:SublimePackages,代码行数:12,代码来源:http_client.py

示例11: _try_server

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def _try_server(self, store_url, path, query_string, data, content_type,
                    content_length):
        request = Request(str(store_url + path + query_string))
        if data is not None:
            request.add_header('Content-Type', content_type)
            request.add_header('Content-Length', content_length)
            try:
                request.add_data
            except AttributeError:
                request.data = data  # python3
            else:
                request.add_data(data)  # python2

        file = urlopen(request)
        status = file.getcode()
        assert status in (200, 204)  # OK, OK-no-data

        # Break early if we're dealing with no-data.
        if status == 204:
            try:
                nothing = file.read()
                assert len(nothing) == 0, nothing
            finally:
                file.close()
            data = None

        # JSON data?
        elif path.endswith('.js'):
            try:
                data = from_jsonfile(utf8_reader(file))
            finally:
                file.close()

        # Binary data?
        elif path.endswith('.bin'):
            # We expect this to be set!
            try:
                file.headers.getheader
            except AttributeError:  # py3
                content_length = file.headers.get('content-length')
                enctype = file.headers.get('x-encryption', 'none')
            else:  # py2
                content_length = file.headers.getheader('content-length')
                enctype = file.headers.getheader('x-encryption', 'none')
            finally:
                length = int(content_length)
            # No file closing here.. the cryptoreader gets to use it.
            data = CryptoReader(fp=file, length=length, enctype=enctype)

        # Unknown data?
        else:
            file.close()
            raise NotImplementedError(path)

        return data
开发者ID:ossobv,项目名称:pstore,代码行数:57,代码来源:server.py

示例12: retrieveBearerToken

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def retrieveBearerToken(self):
        req = Request("https://api.twitter.com/oauth2/token")
        req.method = "POST"
        req.add_header("Authorization", "Basic {}".format(self.key))
        req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        req.data = b"grant_type=client_credentials"

        with urlopen(req) as resp:
            data = json.loads(resp.read().decode())

        self.bearerToken = data["access_token"]
开发者ID:poke,项目名称:twitter-avatar-fetcher,代码行数:13,代码来源:avatar-fetcher.py

示例13: __open

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
	def __open(self, url, headers={}, data=None):
		"""Raw urlopen command"""
		req = Request("%s%s" % (self.url, url), headers=headers)
		try:
			req.data = urlencode(data).encode('utf-8') # Python 3
		except:
			try:
				req.add_data(urlencode(data)) # Python 2
			except:
				pass
		resp = urlopen(req)
		charset = resp.info().get('charset', 'utf-8')
		return json.loads(resp.read().decode(charset))
开发者ID:ogk,项目名称:mytesla,代码行数:15,代码来源:teslajson.py

示例14: _http

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
    def _http(self, url, method, data=None, decoder=None, parse_json=True):
        res = None
        req = Request(url=url)
        req.add_header('Content-Type', 'application/json')
        req.add_header('Hawkular-Tenant', self.tenant_id)
        req.add_header('Host', self.host)

        if self.token is not None:
            req.add_header('Authorization', 'Bearer {0}'.format(self.token))
        elif self.username is not None:
            b64 = base64.b64encode((self.username + ':' + self.password).encode('utf-8'))
            req.add_header('Authorization', 'Basic {0}'.format(b64.decode()))

        if self.authtoken is not None:
            req.add_header('Hawkular-Admin-Token', self.authtoken)

        if not isinstance(data, str):
            data = json.dumps(data, indent=2)

        reader = codecs.getreader('utf-8')

        if data:
            try:
                req.add_data(data)
            except AttributeError:
                req.data = data.encode('utf-8')
        try:
            req.get_method = lambda: method
            res = urlopen(req, context=self.context)

            if parse_json:
                if res.getcode() == 200:
                    data = json.load(reader(res), cls=decoder)
                elif res.getcode() == 204:
                    data = {}
            else:
                data = reader(res).read()

            return data

        except Exception as e:
            self._handle_error(e)

        finally:
            if res:
                res.close()
开发者ID:burmanm,项目名称:hawkular-client-python,代码行数:48,代码来源:client.py

示例15: _CallHttp

# 需要导入模块: from urllib.request import Request [as 别名]
# 或者: from urllib.request.Request import data [as 别名]
 def _CallHttp(self, method, handler, data=None):
     method = method.upper()
     req = Request(self._BuildUri(handler), method=method)
     if isinstance(data, collections.Mapping):
         req.add_header('content-type', 'application/json')
         data = ToUtf8Json(data)
     req.add_header(
         HMAC_HEADER, self._HmacForRequest(method, handler, data))
     req.data = bytes(data, 'utf-8')
     try:
         readData = urlopen(req).read().decode('utf-8')
         return readData
     except HTTPError as err:
         if err.code == 500:
             responseAsJson = json.loads(err.read().decode('utf-8'))
             if responseAsJson['exception']['TYPE'] == "UnknownExtraConf":
                 raise UnknownExtraConf(responseAsJson['exception']['extra_conf_file'])
         raise err
开发者ID:LuckyGeck,项目名称:YcmdCompletion,代码行数:20,代码来源:http_client.py


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