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


Python Request.data方法代码示例

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


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

示例1: proxy_request

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
def proxy_request(service_name, instance_name, path, body=None, headers=None, method="POST"):
    target = get_env("TSURU_TARGET").rstrip("/")
    token = get_env("TSURU_TOKEN")
    url = "{}/services/{}/proxy/{}?callback={}".format(target, service_name, instance_name, path)
    request = Request(url)
    request.add_header("Authorization", "bearer " + token)
    request.get_method = lambda: method
    if body:
        try:
            request.add_data(body)
        except AttributeError:
            request.data = body.encode("utf-8")
    if headers:
        for key, value in headers.items():
            request.add_header(key, value)
    return urlopen(request)
开发者ID:dmvieira,项目名称:rpaas,代码行数:18,代码来源:plugin.py

示例2: proxy_request

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
def proxy_request(service_name, instance_name, method, path, body=None, headers=None):
    target = get_env("TSURU_TARGET").rstrip("/")
    token = get_env("TSURU_TOKEN")

    if not target.startswith("http://") and not target.startswith("https://"):
        target = "http://{}".format(target)

    if instance_name:
        url = "{}/services/{}/proxy/{}?callback=/resources/{}/{}".format(target, service_name, instance_name, instance_name, path.lstrip("/"))
    else:
        url = "{}/services/proxy/service/{}?callback=/resources/{}".format(target, service_name, path.lstrip("/"))

    request = Request(url)
    request.add_header("Authorization", "bearer " + token)
    request.get_method = lambda: method
    if body:
        body = json.dumps(body)
        try:
            request.add_data(body)
        except AttributeError:
            request.data = body.encode('utf-8')

    if headers:
        for header, value in headers.items():
            request.add_header(header, value)

    try:
        return urlopen(request, timeout=30)
    except HTTPError as error:
        return error
    except Exception:
        raise
开发者ID:tsuru,项目名称:healthcheck-as-a-service,代码行数:34,代码来源:plugin.py

示例3: post

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
 def post(self, url, body):
     """
     Internal API for POST request on a OTX URL
     :param url: URL to retrieve
     :param body: HTTP Body to send in request
     :return: response as dict
     """
     request = Request(url)
     request.add_header('X-OTX-API-KEY', self.key)
     request.add_header('User-Agent', self.sdk)
     request.add_header("Content-Type", "application/json")
     method = "POST"
     request.get_method = lambda: method
     if body:
         try:  # python2
             request.add_data(json.dumps(body))
         except AttributeError as ae:  # python3
             request.data = json.dumps(body).encode('utf-8')
     try:
         response = urlopen(request)
         data = response.read().decode('utf-8')
         json_data = json.loads(data)
         return json_data
     except URLError as e:
         if isinstance(e, HTTPError):
             if e.code == 403:
                 raise InvalidAPIKey("Invalid API Key")
             elif e.code == 400:
                 encoded_error = e.read()
                 decoded_error = encoded_error.decode('utf-8')
                 json.loads(decoded_error)
                 raise BadRequest(decoded_error)
     return {}
开发者ID:CyberIntelMafia,项目名称:OTX-Python-SDK,代码行数:35,代码来源:OTXv2.py

示例4: authenticate

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
 def authenticate(self):
     """Authenticate against service api"""
     req = Request(url="%s/tokens" % self.root.service_url)
     req.add_header("Content-Type", "application/json")
     try:
         try:
             req.data = json.dumps({"passwordCredentials": {
                         "useraname": self.root.user,
                         "password": self.root.password}})
             r = json.loads(urlopen(req).read())
             self.root.version = "2.0a"
         except HTTPError:
             print "Got here"
             req.data = '{"auth": %s}' % req.data
             r = json.loads(urlopen(req).read())
             self.root.version = "2.0b"
         self.root.token = r['auth']['token']['id']
     except KeyError:
         raise ValueError("Failed to authenticate to keystone: %s" % r)
开发者ID:willkelly,项目名称:random,代码行数:21,代码来源:keystoneclient.py

示例5: get_token_from_client_credentials

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
def get_token_from_client_credentials(endpoint, client_id, client_secret):
    payload = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'resource': 'https://management.core.windows.net/',
    }
    request = Request(endpoint)
    request.data = urlencode(payload)
    result = urlopen(request)
    return json.loads(result.read())['access_token']
开发者ID:ooha-m,项目名称:test-base,代码行数:13,代码来源:deploy_metabroker.py

示例6: post

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
    def post(cls, url, data=None):
        if data is None:
            data = ""

        req = Request(url)
        req.add_header('Content-Type', 'application/json')
        req.data = data.encode(cls.encoding)

        response = urlopen(req, **cls._config)
        content = response.read()
        response.close()

        return cls.parse_response(response, content=content)
开发者ID:zaabjuda,项目名称:arango-python,代码行数:15,代码来源:urllib2client.py

示例7: _req

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
 def _req(self, method="GET", data=None, xheaders=[], inst=None):
     # make a keystone request
     url = self.admin_url
     if inst:
         url += "/%s" % (inst)
     req = Request(url=url)
     req.data = data
     req.get_method = lambda: method
     req.add_header("X-Auth-Token", self.root.token)
     req.add_header("Content-type", "application/json")
     req.add_header("Accept", "application/json")
     r = urlopen(req).read()
     if r == "":
         return {str(self.oname): None}
     else:
         return json.loads(r)
开发者ID:willkelly,项目名称:random,代码行数:18,代码来源:keystoneclient.py

示例8: parse

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
    def parse(self, source, publicID=None, format="xml", method='POST'):
        """
        Parse source into Graph

        Graph will get loaded into it's own context (sub graph).
        Format defaults to 'xml' (AKA: rdf/xml).

        :returns: Returns the context into which  the source was parsed.

        :param source: source file in the form of
            "http://....." or "~/dir/file.rdf"
        :param publicID: *optional* the logical URI if it's different
            from the physical source URI.
        :param format: must be one of 'xml' or 'n3'
        :param method: must be one of

          * 'POST' -- method adds data to a context
          * 'PUT' -- method replaces data in a context
        """
        url = self.url + '/statements'
        if not (source.startswith('http://') or source.startswith('file://')):
            source = 'file://' + os.path.abspath(os.path.expanduser(source))

        ctx = "<%s>" % (publicID or source)
        url = url + "?" + urlencode(dict(context=ctx))

        req = Request(url)
        req.get_method = lambda: method

        if format == 'xml':
            req.add_header('Content-Type', 'application/rdf+xml')
        elif format == 'n3':
            req.add_header('Content-Type', 'text/rdf+n3')
        else:
            raise "Unknown format: %s" % format

        req.data = urlopen(source).read()
        log.debug("Request: %s" % req.get_full_url())
        try:
            result = urlopen(req).read()
            log.debug("Result: " + result)
        except HTTPError, e:
            # 204 is actually the "success" code
            if e.code == 204:
                return
            log.error(e)
            raise HTTPError(e)
开发者ID:koo5,项目名称:RDFAlchemy,代码行数:49,代码来源:sesame2.py

示例9: put

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
    def put(cls, url, data=None):
        if data is None:
            data = ""

        req = Request(url)
        req.add_header('Content-Type', 'application/json')
        try:
            req.add_data(data.encode(cls.encoding))
        except AttributeError:
            req.data = ("").encode(cls.encoding)
            req.data += data.encode(cls.encoding)
        req.get_method = lambda: "put"
        response = urlopen(req)

        content = response.read()
        response.close()

        return cls.parse_response(response, content=content)
开发者ID:hiroaki-yamamoto,项目名称:arango-python,代码行数:20,代码来源:urllib2client.py

示例10: add

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
    def add(self, xxx_todo_changeme1, context=None):
        """Add a triple with optional context"""
        (s, p, o) = xxx_todo_changeme1
        url = self.url + '/statements'
        ctx = context or self.context
        if ctx:
            url = url + "?" + urlencode(dict(context=ctx))
        req = Request(url)
        # req.data = "%s %s %s .\n" % (
        #     s.n3(), p.n3(), _xmlcharref_encode(o.n3()))
        req.data = "<%s> %s %s .\n" % (
            _xmlcharref_encode(unicode(s)),
            p.n3(),
            _xmlcharref_encode(o.n3()))

        req.add_header('Content-Type', 'text/rdf+n3')
        try:
            result = urlopen(req).read()
        except HTTPError, e:
            if e.code == 204:
                return
            else:
                log.error(e)
开发者ID:koo5,项目名称:RDFAlchemy,代码行数:25,代码来源:sesame2.py

示例11: add

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
            #quote_plus(o.n3().encode("utf-8"))
        if context:
	    ### TODO FIXME what about bnodes like _:adf23123
            query['context']  = "<%s>"%context
        if query:
            url = url+"?"+urlencode(query)
        return url

    def add(self, (s, p, o), context=None):
        """Add a triple with optional context"""
        url = self.url+'/statements'
        ctx = context or self.context
        if ctx:
            url = url+"?"+urlencode(dict(context=ctx))
        req = Request(url)
        req.data = "%s %s %s .\n" % (s.n3(), p.n3(), _xmlcharref_encode(o.n3()))
        req.add_header('Content-Type','text/rdf+n3')
        try:
            result = urlopen(req).read()
        except HTTPError, e:
            if e.code == 204:
                return
            else:
                log.error(e) 
        return result
        
    def remove(self, (s, p, o), context=None):
        """Remove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
开发者ID:pebbie,项目名称:RDFAlchemy,代码行数:33,代码来源:sesame2.py

示例12: attack

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
def attack(url, n, c, **options):
    """
    Test the root url of this site.
    """
    username, key_name, zone, instance_ids = _read_server_list()
    headers = options.get('headers', '')
    csv_filename = options.get("csv_filename", '')
    cookies = options.get('cookies', '')
    post_file = options.get('post_file', '')
    keep_alive = options.get('keep_alive', False)
    basic_auth = options.get('basic_auth', '')

    if csv_filename:
        try:
            stream = open(csv_filename, 'w')
        except IOError as e:
            raise IOError("Specified csv_filename='%s' is not writable. Check permissions or specify a different filename and try again." % csv_filename)

    if not instance_ids:
        print('No bees are ready to attack.')
        return

    print('Connecting to the hive.')

    ec2_connection = boto.ec2.connect_to_region(_get_region(zone))

    print('Assembling bees.')

    reservations = ec2_connection.get_all_instances(instance_ids=instance_ids)

    instances = []

    for reservation in reservations:
        instances.extend(reservation.instances)

    instance_count = len(instances)

    if n < instance_count * 2:
        print('bees: error: the total number of requests must be at least %d (2x num. instances)' % (instance_count * 2))
        return
    if c < instance_count:
        print('bees: error: the number of concurrent requests must be at least %d (num. instances)' % instance_count)
        return
    if n < c:
        print('bees: error: the number of concurrent requests (%d) must be at most the same as number of requests (%d)' % (c, n))
        return

    requests_per_instance = int(float(n) / instance_count)
    connections_per_instance = int(float(c) / instance_count)

    print('Each of %i bees will fire %s rounds, %s at a time.' % (instance_count, requests_per_instance, connections_per_instance))

    params = []

    for i, instance in enumerate(instances):
        params.append({
            'i': i,
            'instance_id': instance.id,
            'instance_name': instance.private_dns_name if instance.public_dns_name == "" else instance.public_dns_name,
            'url': url,
            'concurrent_requests': connections_per_instance,
            'num_requests': requests_per_instance,
            'username': username,
            'key_name': key_name,
            'headers': headers,
            'cookies': cookies,
            'post_file': options.get('post_file'),
            'keep_alive': options.get('keep_alive'),
            'mime_type': options.get('mime_type', ''),
            'tpr': options.get('tpr'),
            'rps': options.get('rps'),
            'basic_auth': options.get('basic_auth')
        })

    print('Stinging URL so it will be cached for the attack.')

    request = Request(url)
    # Need to revisit to support all http verbs.
    if post_file:
        try:
            with open(post_file, 'r') as content_file:
                content = content_file.read()
            if IS_PY2:
                request.add_data(content)
            else:
                # python3 removed add_data method from Request and added data attribute, either bytes or iterable of bytes
                request.data = bytes(content.encode('utf-8'))
        except IOError:
            print('bees: error: The post file you provided doesn\'t exist.')
            return

    if cookies is not '':
        request.add_header('Cookie', cookies)

    if basic_auth is not '':
        authentication = base64.encodestring(basic_auth).replace('\n', '')
        request.add_header('Authorization', 'Basic %s' % authentication)

    # Ping url so it will be cached for testing
    dict_headers = {}
#.........这里部分代码省略.........
开发者ID:alexconlin,项目名称:beeswithmachineguns,代码行数:103,代码来源:bees.py

示例13: add

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
            query['obj']  = o.n3()
        if context:
	    ### TODO FIXME what about bnodes like _:adf23123
            query['context']  = "<%s>"%context
        if query:
            url = url+"?"+urlencode(query)
        return url

    def add(self, (s, p, o), context=None):
        """Add a triple with optional context"""
        url = self.url+'/statements'
        ctx = context or self.context
        if ctx:
            url = url+"?"+urlencode(dict(context=ctx))
        req = Request(url)
        req.data = "%s %s %s .\n" % (s.n3(), p.n3(), o.n3())
        req.add_header('Content-Type','text/rdf+n3')
        try:
            result = urlopen(req).read()
        except HTTPError, e:
            if e.code == 204:
                return
            else:
                log.error(e) 
        return result
        
    def remove(self, (s, p, o), context=None):
        """Remove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
开发者ID:openvest,项目名称:RDFAlchemy,代码行数:33,代码来源:sesame2.py

示例14: sinch_api_request

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
    def sinch_api_request(  # IGNORE:too-many-arguments
        self,
        api_subdomain,
        path,
        data=None,
        method=None,
        authorization_scheme='basic'
    ):
        request = Request(
            '%s%s' % (self.url_prefix_template % api_subdomain, path)
        )

        request.add_header(
            'X-Timestamp', '%sZ' % datetime.utcnow().isoformat()
        )

        # TODO: important note about method before auth
        if method:
            request.get_method = lambda: method

        if data is not None:
            request.data = dumps(data)
            request.add_header('Content-type', 'application/json')

        if authorization_scheme == 'basic':
            request.add_header(
                'Authorization', self.cached_basic_authorization
            )
        elif authorization_scheme == 'public':
            request.add_header(
                'Authorization', self.cached_public_authorization
            )
        elif authorization_scheme == 'user':
            request.add_header('Authorization', self.cached_user_authorization)
        elif authorization_scheme == 'instance':
            request.add_header(
                'Authorization',
                'Instance %s:%s' % (
                    self.cached_instance_authorization['id'],
                    b64encode(
                        new_hmac(
                            b64decode(
                                self.cached_instance_authorization['secret']
                            ),
                            msg=unicode(
                                self._form_string_to_sign(
                                    path,
                                    request,
                                    self._generate_content_md5(request.data)
                                )
                            ),
                            digestmod=sha256
                        ).digest()
                    )
                )
            )
        else:
            # TODO: exception about unknown auth scheme
            pass

        response = urlopen(request).read()
        if response:
            return loads(response)
开发者ID:Bitcall,项目名称:pysinch,代码行数:65,代码来源:pysinch.py

示例15: urlencode

# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import data [as 别名]
        if context:
            ### TODO FIXME what about bnodes like _:adf23123
            query["context"] = "<%s>" % context
        if query:
            url = url + "?" + urlencode(query)
        return url

    def add(self, (s, p, o), context=None):
        """Add a triple with optional context"""
        url = self.url + "/statements"
        ctx = context or self.context
        if ctx:
            url = url + "?" + urlencode(dict(context=ctx))
        req = Request(url)
        # req.data = "%s %s %s .\n" % (s.n3(), p.n3(), _xmlcharref_encode(o.n3()))
        req.data = "<%s> %s %s .\n" % (_xmlcharref_encode(unicode(s)), p.n3(), _xmlcharref_encode(o.n3()))
        req.add_header("Content-Type", "text/rdf+n3")
        try:
            result = urlopen(req).read()
        except HTTPError, e:
            if e.code == 204:
                return
            else:
                log.error(e)
        return result

    def remove(self, (s, p, o), context=None):
        """Remove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
开发者ID:quinode,项目名称:RDFAlchemy,代码行数:33,代码来源:sesame2.py


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