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


Python Request.get_method方法代码示例

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


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

示例1: build_request_with_data

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
def build_request_with_data(url, data, api_key, method):
    """Build a request with the received method."""
    http_redirect_with_data_handler = HTTPRedirectWithDataHandler(method=method)
    opener = build_opener(http_redirect_with_data_handler)
    install_opener(opener)
    url = make_url(url, api_key=api_key, args=None)
    request = Request(url, headers={'Content-Type': 'application/json'}, data=json.dumps(data))
    request_method = request.get_method()
    if request_method != method:
        request.get_method = lambda: method
    return opener, request
开发者ID:ImmPortDB,项目名称:immport-galaxy,代码行数:13,代码来源:common.py

示例2: redirect_request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
 def redirect_request(self, request, fp, code, msg, headers, new_url):
     request_method = request.get_method()
     if str(code) in self.redirect_codes and request_method in self.valid_methods:
         new_url = new_url.replace(' ', '%20')
         request = Request(new_url,
                           data=request.data,
                           headers=request.headers,
                           origin_req_host=request.get_origin_req_host(),
                           unverifiable=True)
         if self.method in self.valid_methods:
             if request.get_method() != self.method:
                 request.get_method = lambda: self.method
         return request
     else:
         HTTPRedirectHandler.redirect_request(request, fp, code, msg, headers, new_url)
开发者ID:ImmPortDB,项目名称:immport-galaxy,代码行数:17,代码来源:common.py

示例3: _pd_api

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def _pd_api(self, url, data=None, method='GET'):
        url = '%s/%s' % (PD_API_BASE, url)
        request_args = {
            'headers': dict(self._pd_headers)
        }
        if six.PY3:  # pragma: no cover
            request_args['method'] = method

        if data is not None:
            request_args['data'] = json.dumps(data).encode('utf-8')
            request_args['headers']['Content-Type'] = APPLICATION_JSON

        request = Request(url, **request_args)
        if six.PY2:  # pragma: no cover
            request.get_method = lambda: method

        try:
            response = urlopen(request)
            return json.loads(response.read().decode('utf-8'))
        except HTTPError as e:
            response = e.read().decode('utf-8')
            logger.warning("API error: %s", response)
            if method == 'GET' and e.code == 404:
                return None
            else:
                raise e
开发者ID:pebble,项目名称:spacel-provision,代码行数:28,代码来源:pagerduty.py

示例4: get_genome_space_launch_apps

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
def get_genome_space_launch_apps( atm_url, url_opener, file_url, file_type ):
    gs_request = Request( "%s/%s/webtool/descriptor" % ( atm_url, GENOMESPACE_API_VERSION_STRING ) )
    gs_request.get_method = lambda: 'GET'
    opened_gs_request = url_opener.open( gs_request )
    webtool_descriptors = json.loads( opened_gs_request.read() )
    webtools = []
    for webtool in webtool_descriptors:
        webtool_name = webtool.get( 'name' )
        base_url = webtool.get( 'baseUrl' )
        use_tool = False
        for param in webtool.get( 'fileParameters', [] ):
            for format in param.get( 'formats', [] ):
                if format.get( 'name' ) == file_type:
                    use_tool = True
                    break
            if use_tool:
                file_param_name = param.get( 'name' )
                # file_name_delimiters = param.get( 'nameDelimiters' )
                if '?' in base_url:
                    url_delimiter = "&"
                else:
                    url_delimiter = "?"
                launch_url = "%s%s%s" % ( base_url, url_delimiter, urlencode( [ ( file_param_name, file_url ) ] ) )
                webtools.append( ( launch_url, webtool_name ) )
                break
    return webtools
开发者ID:ashvark,项目名称:galaxy,代码行数:28,代码来源:genomespace_exporter.py

示例5: execute

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw):
        """
        if batch == False, execute a command with the given parameters and
        return the response JSON.
        If batch == True, return the dictionary that would be used in a batch
        command.
        """
        if batch:
            urlsplitter = urlparse(API_ROOT).netloc
            ret = {"method": http_verb, "path": uri.split(urlsplitter, 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        if _body is None:
            data = kw and json.dumps(kw, default=date_handler) or "{}"
        else:
            data = _body
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            data = data

        headers = {
            'Content-type': 'application/json',
            'X-Parse-Application-Id': app_id,
            'X-Parse-REST-API-Key': rest_key
        }
        headers.update(extra_headers or {})

        request = Request(url.encode('utf-8'), data, headers)

        if ACCESS_KEYS.get('session_token'):
            request.add_header('X-Parse-Session-Token', ACCESS_KEYS.get('session_token'))
        elif master_key:
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request, timeout=CONNECTION_TIMEOUT)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
开发者ID:sunsongxp,项目名称:ParsePy,代码行数:62,代码来源:connection.py

示例6: set_genomespace_format_identifiers

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
def set_genomespace_format_identifiers( url_opener, dm_site ):
    gs_request = Request( "%s/%s/dataformat/list" % ( dm_site, GENOMESPACE_API_VERSION_STRING ) )
    gs_request.get_method = lambda: 'GET'
    opened_gs_request = url_opener.open( gs_request )
    genomespace_formats = json.loads( opened_gs_request.read() )
    for format in genomespace_formats:
        GENOMESPACE_FORMAT_IDENTIFIER_TO_GENOMESPACE_EXT[ format['url'] ] = format['name']
开发者ID:ashvark,项目名称:galaxy,代码行数:9,代码来源:genomespace_importer.py

示例7: _request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def _request(self, url, data=None, headers=None, checker=None, method=None):
        if not headers:
            headers = {}
        if self.token:
            headers["X-API-Key"] = self.token
        self.log.debug("Request: %s %s %s", method if method else 'GET', url,
                       data[:self.logger_limit] if data else None)
        # .encode("utf-8") is probably better
        data = data.encode() if isinstance(data, six.text_type) else data
        request = Request(url, data, headers)
        if method:
            request.get_method = lambda: method

        response = urlopen(request, timeout=self.timeout)

        if checker:
            checker(response)

        resp = response.read()

        if not isinstance(resp, str):
            resp = resp.decode()

        self.log.debug("Response: %s", resp[:self.logger_limit] if resp else None)
        return json.loads(resp) if len(resp) else {}
开发者ID:Yingmin-Li,项目名称:taurus,代码行数:27,代码来源:blazemeter.py

示例8: __del

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
def __del(api_key, url, data):
    """
    Do the actual DELETE
    """
    url = make_url(api_key, url)
    req = Request(url, headers={'Content-Type': 'application/json'}, data=json.dumps(data))
    req.get_method = lambda: 'DELETE'
    return json.loads(urlopen(req).read())
开发者ID:ImmPortDB,项目名称:immport-galaxy,代码行数:10,代码来源:common.py

示例9: create_directory

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
def create_directory( url_opener, directory_dict, new_dir, dm_url ):
    payload = { "isDirectory": True }
    for dir_slice in new_dir:
        if dir_slice in ( '', '/', None ):
            continue
        url = '/'.join( ( directory_dict['url'], quote( dir_slice.replace( '/', '_' ), safe='' ) ) )
        new_dir_request = Request( url, headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }, data=json.dumps( payload ) )
        new_dir_request.get_method = lambda: 'PUT'
        directory_dict = json.loads( url_opener.open( new_dir_request ).read() )
    return directory_dict
开发者ID:ashvark,项目名称:galaxy,代码行数:12,代码来源:genomespace_exporter.py

示例10: clear_all_queries

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
 def clear_all_queries(self, cluster_name=DEFAULT_CLUSTER):
     """
     Clear all the primed queries from a particular cluster
     :param cluster_name: cluster to clear queries from
     """
     opener = build_opener(HTTPHandler)
     request = Request("http://{0}/{1}/{2}".format(
         self.admin_addr, "prime", cluster_name))
     request.get_method = lambda: 'DELETE'
     connection = opener.open(request)
     return connection.read()
开发者ID:thelastpickle,项目名称:python-driver,代码行数:13,代码来源:utils.py

示例11: submit_request

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def submit_request(self, query):
        opener = build_opener(HTTPHandler)
        data = json.dumps(query.fetch_json()).encode('utf8')

        request = Request("http://{}/{}{}".format(
            self.admin_addr, query.path, query.fetch_url_params()), data=data)
        request.get_method = lambda: 'POST'
        request.add_header("Content-Type", 'application/json')
        request.add_header("Content-Length", len(data))

        connection = opener.open(request)
        return connection.read().decode('utf-8')
开发者ID:thelastpickle,项目名称:python-driver,代码行数:14,代码来源:utils.py

示例12: req

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
 def req(self, path, data=None, method=None):
     url = self.server + path
     if data:
         req = Request(url, headers={'Content-Type': 'application/json'}, data=json.dumps(data))
     else:
         req = Request(url, headers={'Content-Type': 'application/json'})
     if method:
         req.get_method = lambda: method
     res = self.opener.open(req)
     print('==> at %s (%s)' % (url, method or 'GET'))
     assert res.getcode() == 200, url
     return res
开发者ID:ImmPortDB,项目名称:immport-galaxy,代码行数:14,代码来源:check_galaxy.py

示例13: execute

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def execute(cls, uri, http_verb, extra_headers=None, batch=False, **kw):
        """
        if batch == False, execute a command with the given parameters and
        return the response JSON.
        If batch == True, return the dictionary that would be used in a batch
        command.
        """
        if batch:
            ret = {"method": http_verb, "path": uri.split("parse.com", 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        headers = extra_headers or {}
        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        data = kw and json.dumps(kw) or "{}"
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            data = data.encode('utf-8')

        request = Request(url, data, headers)
        request.add_header('Content-type', 'application/json')
        request.add_header('X-Parse-Application-Id', app_id)
        request.add_header('X-Parse-REST-API-Key', rest_key)

        if master_key and 'X-Parse-Session-Token' not in headers.keys():
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
开发者ID:shawnp,项目名称:ParsePy,代码行数:53,代码来源:connection.py

示例14: upload

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
    def upload(self, filename):
        if not self.cdash_upload_url:
            return

        # Compute md5 checksum for the contents of this file.
        md5sum = checksum(hashlib.md5, filename, block_size=8192)

        opener = build_opener(HTTPHandler)
        with open(filename, 'rb') as f:
            url = "{0}&MD5={1}".format(self.cdash_upload_url, md5sum)
            request = Request(url, data=f)
            request.add_header('Content-Type', 'text/xml')
            request.add_header('Content-Length', os.path.getsize(filename))
            # By default, urllib2 only support GET and POST.
            # CDash needs expects this file to be uploaded via PUT.
            request.get_method = lambda: 'PUT'
            url = opener.open(request)
开发者ID:matzke1,项目名称:spack,代码行数:19,代码来源:cdash.py

示例15: recurse_directory_dict

# 需要导入模块: from six.moves.urllib.request import Request [as 别名]
# 或者: from six.moves.urllib.request.Request import get_method [as 别名]
 def recurse_directory_dict( url_opener, cur_options, url ):
     cur_directory = Request( url, headers={ 'Content-Type': 'application/json', 'Accept': 'application/json, text/plain' } )
     cur_directory.get_method = lambda: 'GET'
     # get url to upload to
     try:
         cur_directory = url_opener.open( cur_directory ).read()
     except HTTPError as e:
         log.debug( 'GenomeSpace export tool failed reading a directory "%s": %s' % ( url, e ) )
         return  # bad url, go to next
     cur_directory = json.loads( cur_directory )
     directory = cur_directory.get( 'directory', {} )
     contents = cur_directory.get( 'contents', [] )
     if directory.get( 'isDirectory', False ):
         selected = directory.get( 'path' ) == value
         cur_options.append( { 'name': directory.get( 'name' ), 'value': directory.get( 'path'), 'options': [], 'selected': selected  } )
         for sub_dir in contents:
             if sub_dir.get( 'isDirectory', False ):
                 recurse_directory_dict( url_opener, cur_options[-1]['options'], sub_dir.get( 'url' ) )
开发者ID:ashvark,项目名称:galaxy,代码行数:20,代码来源:genomespace_exporter.py


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