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


Python CaseInsensitiveDict.pop方法代码示例

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


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

示例1: prepare_response

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
    def prepare_response(self, cached):
        """Verify our vary headers match and construct a real urllib3
        HTTPResponse object.
        """
        # Special case the '*' Vary value as it means we cannot actually
        # determine if the cached response is suitable for this request.
        if "*" in cached.get("vary", {}):
            return

        body_raw = cached["response"].pop("body")

        headers = CaseInsensitiveDict(data=cached['response']['headers'])
        if headers.get('transfer-encoding', '') == 'chunked':
            headers.pop('transfer-encoding')

        cached['response']['headers'] = headers

        try:
            body = io.BytesIO(body_raw)
        except TypeError:
            # This can happen if cachecontrol serialized to v1 format (pickle)
            # using Python 2. A Python 2 str(byte string) will be unpickled as
            # a Python 3 str (unicode string), which will cause the above to
            # fail with:
            #
            #     TypeError: 'str' does not support the buffer interface
            body = io.BytesIO(body_raw.encode('utf8'))

        return HTTPResponse(
            body=body,
            preload_content=False,
            **cached["response"]
        )
开发者ID:RyPeck,项目名称:cbapi-python,代码行数:35,代码来源:serialize.py

示例2: set_extra_headers

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
 def set_extra_headers(self, headers):
     header_dict = CaseInsensitiveDict(headers)
     if 'Reply-To' in header_dict:
         self.data["ReplyTo"] = header_dict.pop('Reply-To')
     self.data["Headers"] = [
         {"Name": key, "Value": value}
         for key, value in header_dict.items()
     ]
开发者ID:c-mrf,项目名称:django-anymail,代码行数:10,代码来源:postmark.py

示例3: retrieve

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
    def retrieve(self, request):

        filename = self._fn(request.url)
        resp = Response()

        headers = utils.read('%s.metadata' % filename)
        if headers:
            try:
                headers = CaseInsensitiveDict(json.loads(headers))
            except ValueError:
                return None
            headers['x-cache'] = 'HIT from %s' % self.__class__.__name__
            resp.url = headers.pop('url', None)
            resp.status_code = headers.pop('status-code', None)
            resp.encoding = headers.pop('encoding', None)
            resp.headers = headers
            resp._content = utils.read(filename)
            return resp
        else:
            return None
开发者ID:ownport,项目名称:webpage,代码行数:22,代码来源:cache.py

示例4: verify_signature

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
    def verify_signature(self, query_parameters):
        """Verify the signature provided with the query parameters.

        http://docs.shopify.com/api/tutorials/oauth

        example usage::

            from shopify_trois import Credentials
            from shopify_trois.engines import Json as Shopify
            from urllib.parse import parse_qsl

            credentials = Credentials(
                api_key='your_api_key',
                scope=['read_orders'],
                secret='your_app_secret'
            )

            shopify = Shopify(shop_name="your_store_name", credentials=\
                    credentials)

            query_parameters = parse_qsl("code=238420989938cb70a609f6ece2e2586\
b&shop=yourstore.myshopify.com&timestamp=1373382939&\
signature=6fb122e33c21851c465345b8cb97245e")

            if not shopify.verify_signature(query_parameters):
                raise Exception("invalid signature")

            credentials.code = dict(query_parameters).get('code')

            shopify.setup_access_token()

        :returns: Returns True if the signature is valid.

        """
        params = CaseInsensitiveDict(query_parameters)
        signature = params.pop("signature", None)

        calculated = ["%s=%s" % (k, v) for k, v in params.items()]
        calculated.sort()
        calculated = "".join(calculated)

        calculated = "{secret}{calculated}".format(
            secret=self.credentials.secret,
            calculated=calculated
        )

        md5 = hashlib.md5()
        md5.update(calculated.encode('utf-8'))

        produced = md5.hexdigest()

        return produced == signature
开发者ID:RafaAguilar,项目名称:shopify-trois,代码行数:54,代码来源:oauth_engine.py

示例5: prepare_response

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
    def prepare_response(self, request, cached):
        """Verify our vary headers match and construct a real urllib3
        HTTPResponse object.
        """
        # Special case the '*' Vary value as it means we cannot actually
        # determine if the cached response is suitable for this request.
        # This case is also handled in the controller code when creating
        # a cache entry, but is left here for backwards compatibility.
        if "*" in cached.get("vary", {}):
            return

        # Ensure that the Vary headers for the cached response match our
        # request
        for header, value in cached.get("vary", {}).items():
            if request.headers.get(header, None) != value:
                return

        body_raw = cached["response"].pop("body")

        headers = CaseInsensitiveDict(data=cached["response"]["headers"])
        if headers.get("transfer-encoding", "") == "chunked":
            headers.pop("transfer-encoding")

        cached["response"]["headers"] = headers

        try:
            body = io.BytesIO(body_raw)
        except TypeError:
            # This can happen if cachecontrol serialized to v1 format (pickle)
            # using Python 2. A Python 2 str(byte string) will be unpickled as
            # a Python 3 str (unicode string), which will cause the above to
            # fail with:
            #
            #     TypeError: 'str' does not support the buffer interface
            body = io.BytesIO(body_raw.encode("utf8"))

        return HTTPResponse(body=body, preload_content=False, **cached["response"])
开发者ID:ionrock,项目名称:cachecontrol,代码行数:39,代码来源:serialize.py

示例6: __request_callback

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
    def __request_callback(self, request, uri, response_headers):
        self.__readNextRequest(self.__cnx.verb, self.__cnx.url, self.__cnx.input, self.__cnx.headers)

        status = int(readLine(self.__file))
        self.response_headers = CaseInsensitiveDict(eval(readLine(self.__file)))
        output = readLine(self.__file)
        readLine(self.__file)

        if atLeastPython3:
            output = bytes(output, 'utf-8')

        # make a copy of the headers and remove the ones that interfere with the response handling
        adding_headers = CaseInsensitiveDict(self.response_headers)
        adding_headers.pop('content-length', None)
        adding_headers.pop('transfer-encoding', None)
        adding_headers.pop('content-encoding', None)

        response_headers.update(adding_headers)
        return [status, response_headers, output]
开发者ID:ahmad88me,项目名称:PyGithub,代码行数:21,代码来源:Framework.py

示例7: sniffit

# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import pop [as 别名]
def sniffit():
    """
    Perform an HTTP/HTTPS request to the address that the user specifid
    :return:

    TODO Make the Google Verification a separate module with annotion
    """
    parsed_url = urlparse(request.json["url"])
    app.logger.info(request.remote_addr + " " + parsed_url.netloc)

    # Processing the headers to be sent to the URL that the user defined in the interface.
    # What we are doing here is making sure the the user can't override some headers that we want to force such as
    # X-Forwarded-For.
    request_headers = CaseInsensitiveDict({header["key"]: header["value"] for header in request.json["headers"]})

    request_headers["X-Forwarded-For"] = request.remote_addr
    request_headers["X-Anti-Abuse"] = app.config.get("ABUSE_CONTACT")

    request_headers = {string.capwords(k, "-"): v for (k, v) in request_headers.items()}

    # Request Parameters
    if type(request.json["parameters"]) is list:
        request_parameters = "&".join([cgi.escape(header["key"])+"="+cgi.escape(header["value"]) for header in request.json["parameters"]])
    else:
        request_parameters = request.json["parameters"]

    # Base Response JSON
    response_json = {'success': False, 'sniffed': None, 'messages': []}

    try:
        if string.lower(request.json["method"]) in ["get", "head", "options"]:
            response = requests.request(request.json["method"], request.json["url"], verify=False,
                                        params=request_parameters, headers=request_headers)
        else:
            response = requests.request(request.json["method"], request.json["url"],
                                        verify=False, data=request_parameters, headers=request_headers)

        # I prefer to have the capitalized headers in the frontend
        # This will convert the headers from 'content-type' to 'Content-Type'
        response_headers = {string.capwords(k, "-"): v for (k, v) in response.headers.items()}

        # This is for the adrministrators only so there is no need for the end-user to see this
        request_headers.pop("X-Anti-Abuse")
        request_headers.pop("X-Forwarded-For")

        # Create a history of redirects to inform the user
        redirections = [{"url": redirect.headers["location"]} for redirect in response.history]

        # Geo Location
        ipaddress = socket.gethostbyname(parsed_url.netloc)
        geolocation_response = requests.get("http://ip-api.com/json/" + ipaddress);

        response_json["success"] = True
        response_json["showRecaptcha"] = recaptcha_handler.is_token_invalid()
        response_json["sniffed"] = {
            'headers': {
                'response': response_headers,
                'request': request_headers
            },
            'ipaddress': ipaddress,
            'geolocation': geolocation_response.json(),
            'ssl': None,
            'redirect': redirections,
            'body': base64.b64encode(cgi.escape(response.text.encode("UTF-8"))),
            'size': response.headers.get("content-length", False),
            'ssize': len(response.text.encode("UTF-8")),
            'elapsed': response.elapsed.total_seconds(),
            'status': {
                "reason": response.reason,
                "code": str(response.status_code)
            }
        }
    except Exception as e:
        raise RequestFailedException(repr(e))

    return jsonify(response_json)
开发者ID:rvelhote,项目名称:sniffr,代码行数:78,代码来源:sniffr.py


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