• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python http_cookies.SimpleCookie类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.moves.http_cookies.SimpleCookie的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie类的具体用法?Python SimpleCookie怎么用?Python SimpleCookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: make_cookie

def make_cookie(name, load, seed, expire=0, domain="", path="",
                timestamp=""):
    """
    Create and return a cookie

    :param name: Cookie name
    :param load: Cookie load
    :param seed: A seed for the HMAC function
    :param expire: Number of minutes before this cookie goes stale
    :param domain: The domain of the cookie
    :param path: The path specification for the cookie
    :return: A tuple to be added to headers
    """
    cookie = SimpleCookie()
    if not timestamp:
        timestamp = str(int(time.mktime(time.gmtime())))
    signature = cookie_signature(seed, load, timestamp)
    cookie[name] = "|".join([load, timestamp, signature])
    if path:
        cookie[name]["path"] = path
    if domain:
        cookie[name]["domain"] = domain
    if expire:
        cookie[name]["expires"] = _expiration(expire,
                                              "%a, %d-%b-%Y %H:%M:%S GMT")

    return tuple(cookie.output().split(": ", 1))
开发者ID:HaToHo,项目名称:pysaml2,代码行数:27,代码来源:httputil.py


示例2: _prepare_response

    def _prepare_response(self, res_info, url):

        res = requests.Response()
        res.url = res_info.get('url', url)
        res.status_code = res_info.get('status_code', 200)
        res.reason_phrase = res_info.get('reason_phrase', REASON_PHRASES.get(res.status_code, 'UNKNOWN STATUS CODE'))

        if 'reason' in res_info:
            res.reason = res_info['reason']

        if 'headers' in res_info:
            res.headers.update(res_info['headers'])

            if 'Set-Cookie' in res_info['headers'] and 'cookies' not in res_info:
                cookies = SimpleCookie()
                for entry in res_info['headers']['Set-Cookie'].split(','):
                    cookies.load(str(entry))
                res.cookies.update(cookies)

        if 'cookies' in res_info:
            res.cookies.update(res_info['cookies'])

        res.raw = StreamContent(res_info.get('content', ''))

        return res
开发者ID:Wirecloud,项目名称:wirecloud,代码行数:25,代码来源:testcases.py


示例3: cookie_parts

def cookie_parts(name, kaka):
    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)
    if morsel:
        return morsel.value.split("|")
    else:
        return None
开发者ID:HaToHo,项目名称:pysaml2,代码行数:7,代码来源:httputil.py


示例4: set_cookie

def set_cookie(name, _, *args):
    cookie = SimpleCookie()
    cookie[name] = base64.b64encode(":".join(args))
    cookie[name]['path'] = "/"
    cookie[name]["expires"] = _expiration(5)  # 5 minutes from now
    logger.debug("Cookie expires: %s", cookie[name]["expires"])
    return tuple(cookie.output().split(": ", 1))
开发者ID:jkakavas,项目名称:pysaml2,代码行数:7,代码来源:idp.py


示例5: CookieHandler

class CookieHandler(object):

    def __init__(self, *args, **kw):
        # Somewhere to store cookies between consecutive requests
        self.cookies = SimpleCookie()
        super(CookieHandler, self).__init__(*args, **kw)

    def httpCookie(self, path):
        """Return self.cookies as an HTTP_COOKIE environment value."""
        l = [m.OutputString().split(';')[0] for m in self.cookies.values()
             if path.startswith(m['path'])]
        return '; '.join(l)

    def loadCookies(self, envstring):
        self.cookies.load(envstring)

    def saveCookies(self, response):
        """Save cookies from the response."""
        # Urgh - need to play with the response's privates to extract
        # cookies that have been set
        # TODO: extend the IHTTPRequest interface to allow access to all
        # cookies
        # TODO: handle cookie expirations
        for k, v in response._cookies.items():
            k = k.encode('utf8') if bytes is str else k
            val = v['value']
            val = val.encode('utf8') if bytes is str else val
            self.cookies[k] = val
            if 'path' in v:
                self.cookies[k]['path'] = v['path']
开发者ID:zopefoundation,项目名称:zope.app.testing,代码行数:30,代码来源:functional.py


示例6: parse_cookie

def parse_cookie(name, seed, kaka):
    """Parses and verifies a cookie value

    :param seed: A seed used for the HMAC signature
    :param kaka: The cookie
    :return: A tuple consisting of (payload, timestamp)
    """
    if not kaka:
        return None

    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)

    if morsel:
        parts = morsel.value.split("|")
        if len(parts) != 3:
            return None
            # verify the cookie signature
        sig = cookie_signature(seed, parts[0], parts[1])
        if sig != parts[2]:
            raise SAMLError("Invalid cookie signature")

        try:
            return parts[0].strip(), parts[1]
        except KeyError:
            return None
    else:
        return None
开发者ID:HaToHo,项目名称:pysaml2,代码行数:28,代码来源:httputil.py


示例7: _assert_cookies_expired

    def _assert_cookies_expired(self, http_headers):
        cookies_string = ";".join([c[1] for c in http_headers if c[0] == "Set-Cookie"])
        all_cookies = SimpleCookie()
        all_cookies.load(cookies_string)

        now = datetime.datetime.utcnow()  #
        for c in [self.provider.cookie_name, self.provider.session_cookie_name]:
            dt = datetime.datetime.strptime(all_cookies[c]["expires"], "%a, %d-%b-%Y %H:%M:%S GMT")
            assert dt < now  # make sure the cookies have expired to be cleared
开发者ID:htobenothing,项目名称:pyoidc,代码行数:9,代码来源:test_oic_provider.py


示例8: set_cookie

 def set_cookie(self, user):
     uid = rndstr(32)
     self.uid2user[uid] = user
     cookie = SimpleCookie()
     cookie[self.cookie_name] = uid
     cookie[self.cookie_name]['path'] = "/"
     cookie[self.cookie_name]["expires"] = _expiration(480)
     logger.debug("Cookie expires: %s", cookie[self.cookie_name]["expires"])
     return cookie.output().encode("UTF-8").split(": ", 1)
开发者ID:Lefford,项目名称:pysaml2,代码行数:9,代码来源:sp.py


示例9: cookies

    def cookies(self):
        if self._cookies is None:
            parser = SimpleCookie(self.headers("Cookie"))
            cookies = {}
            for morsel in parser.values():
                cookies[morsel.key] = morsel.value

            self._cookies = cookies

        return self._cookies.copy()
开发者ID:dkraczkowski,项目名称:bolt,代码行数:10,代码来源:http.py


示例10: cookies

    def cookies(self):
        if self._cookies is None:
            # NOTE(tbug): We might want to look into parsing
            # cookies ourselves. The SimpleCookie is doing a
            # lot if stuff only required to SEND cookies.
            parser = SimpleCookie(self.get_header("Cookie"))
            cookies = {}
            for morsel in parser.values():
                cookies[morsel.key] = morsel.value

            self._cookies = cookies

        return self._cookies.copy()
开发者ID:openarmy,项目名称:falcon,代码行数:13,代码来源:request.py


示例11: delete_cookie

def delete_cookie(environ, name):
    kaka = environ.get("HTTP_COOKIE", "")
    logger.debug("delete KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get(name, None)
        cookie = SimpleCookie()
        cookie[name] = ""
        cookie[name]["path"] = "/"
        logger.debug("Expire: %s", morsel)
        cookie[name]["expires"] = _expiration("dawn")
        return tuple(cookie.output().split(": ", 1))
    return None
开发者ID:tophatmonocle,项目名称:pysaml2,代码行数:13,代码来源:idp.py


示例12: delete_cookie

 def delete_cookie(self, environ):
     cookie = environ.get("HTTP_COOKIE", '')
     logger.debug("delete cookie: %s", cookie)
     if cookie:
         _name = self.cookie_name
         cookie_obj = SimpleCookie(cookie)
         morsel = cookie_obj.get(_name, None)
         cookie = SimpleCookie()
         cookie[_name] = ""
         cookie[_name]['path'] = "/"
         logger.debug("Expire: %s", morsel)
         cookie[_name]["expires"] = _expiration("now")
         return cookie.output().split(": ", 1)
     return None
开发者ID:Lefford,项目名称:pysaml2,代码行数:14,代码来源:sp.py


示例13: info_from_cookie

def info_from_cookie(kaka):
    logger.debug("KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get("idpauthn", None)
        if morsel:
            try:
                key, ref = base64.b64decode(morsel.value).split(":")
                return IDP.cache.uid2user[key], ref
            except (KeyError, TypeError):
                return None, None
        else:
            logger.debug("No idpauthn cookie")
    return None, None
开发者ID:jkakavas,项目名称:pysaml2,代码行数:14,代码来源:idp.py


示例14: get_user

    def get_user(self, environ):
        cookie = environ.get("HTTP_COOKIE", '')
        logger.debug("Cookie: %s", cookie)
        if cookie:
            cookie_obj = SimpleCookie(cookie)
            morsel = cookie_obj.get(self.cookie_name, None)
            if morsel:
                try:
                    return self.uid2user[morsel.value]
                except KeyError:
                    return None
            else:
                logger.debug("No %s cookie", self.cookie_name)

        return None
开发者ID:Lefford,项目名称:pysaml2,代码行数:15,代码来源:sp.py


示例15: __init__

 def __init__( self ):
     """
     Create a new Response defaulting to HTML content and "200 OK" status
     """
     self.status = "200 OK"
     self.headers = HeaderDict( { "content-type": "text/html" } )
     self.cookies = SimpleCookie()
开发者ID:ashvark,项目名称:galaxy,代码行数:7,代码来源:base.py


示例16: __init__

    def __init__(self, d):
        """Takes headers as a dict, list, or bytestring.
        """
        if isinstance(d, bytes):
            from pando.exceptions import MalformedHeader

            def genheaders():
                for line in d.splitlines():
                    if b':' not in line:
                        # no colon separator in header
                        raise MalformedHeader(line)
                    k, v = line.split(b':', 1)
                    if k != k.strip():
                        # disallowed leading or trailing whitspace
                        # (per http://tools.ietf.org/html/rfc7230#section-3.2.4)
                        raise MalformedHeader(line)
                    yield k, v.strip()

            headers = genheaders()
        else:
            headers = d
        CaseInsensitiveMapping.__init__(self, headers)

        # Cookie
        # ======

        self.cookie = SimpleCookie()
        cookie = self.get(b'Cookie', b'')
        if PY3 and isinstance(cookie, bytes):
            cookie = cookie.decode('ascii', 'replace')
        try:
            self.cookie.load(cookie)
        except CookieError:
            pass  # XXX really?
开发者ID:AspenWeb,项目名称:pando.py,代码行数:34,代码来源:baseheaders.py


示例17: set_cookie

def set_cookie(name, _, *args):
    cookie = SimpleCookie()

    data = ":".join(args)
    if not isinstance(data, six.binary_type):
        data = data.encode("ascii")

    data64 = base64.b64encode(data)
    if not isinstance(data64, six.string_types):
        data64 = data64.decode("ascii")

    cookie[name] = data64
    cookie[name]["path"] = "/"
    cookie[name]["expires"] = _expiration(5)  # 5 minutes from now
    logger.debug("Cookie expires: %s", cookie[name]["expires"])
    return tuple(cookie.output().split(": ", 1))
开发者ID:tophatmonocle,项目名称:pysaml2,代码行数:16,代码来源:idp.py


示例18: info_from_cookie

def info_from_cookie(kaka):
    logger.debug("KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get("idpauthn", None)
        if morsel:
            try:
                data = base64.b64decode(morsel.value)
                if not isinstance(data, six.string_types):
                    data = data.decode("ascii")
                key, ref = data.split(":", 1)
                return IDP.cache.uid2user[key], ref
            except (KeyError, TypeError):
                return None, None
        else:
            logger.debug("No idpauthn cookie")
    return None, None
开发者ID:tophatmonocle,项目名称:pysaml2,代码行数:17,代码来源:idp.py


示例19: extract_macaroons

def extract_macaroons(headers_or_request):
    ''' Returns an array of any macaroons found in the given slice of cookies.
    If the argument implements a get_header method, that will be used
    instead of the get method to retrieve headers.
    @param headers_or_request: dict of headers or a
    urllib.request.Request-like object.
    @return: A list of list of mpy macaroons
    '''
    def get_header(key, default=None):
        try:
            return headers_or_request.get_header(key, default)
        except AttributeError:
            return headers_or_request.get(key, default)

    mss = []

    def add_macaroon(data):
        try:
            data = utils.b64decode(data)
            data_as_objs = json.loads(data.decode('utf-8'))
        except ValueError:
            return
        ms = [utils.macaroon_from_dict(x) for x in data_as_objs]
        mss.append(ms)

    cookie_header = get_header('Cookie')
    if cookie_header is not None:
        cs = SimpleCookie()
        # The cookie might be a unicode object, so convert it
        # to ASCII. This may cause an exception under Python 2.
        # TODO is that a problem?
        cs.load(str(cookie_header))
        for c in cs:
            if c.startswith('macaroon-'):
                add_macaroon(cs[c].value)
    # Python doesn't make it easy to have multiple values for a
    # key, so split the header instead, which is necessary
    # for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2)
    macaroon_header = get_header('Macaroons')
    if macaroon_header is not None:
        for h in macaroon_header.split(','):
            add_macaroon(h)
    return mss
开发者ID:go-macaroon-bakery,项目名称:py-macaroon-bakery,代码行数:43,代码来源:_client.py


示例20: _prepare_response

    def _prepare_response(self, res_info, url):

        res = requests.Response()
        res.url = res_info.get("url", url)
        res.status_code = res_info.get("status_code", 200)
        res.reason_phrase = res_info.get("reason_phrase", REASON_PHRASES.get(res.status_code, "UNKNOWN STATUS CODE"))

        if "reason" in res_info:
            res.reason = res_info["reason"]

        if "headers" in res_info:
            res.headers.update(res_info["headers"])

            if "Set-Cookie" in res_info["headers"]:
                cookies = SimpleCookie()
                for entry in res_info["headers"]["Set-Cookie"].split(","):
                    cookies.load(str(entry))
                res.cookies.update(cookies)

        res.raw = StreamContent(res_info.get("content", ""))

        return res
开发者ID:GreenIDer-Donati,项目名称:wirecloud,代码行数:22,代码来源:testcases.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mock.call函数代码示例发布时间:2022-05-27
下一篇:
Python http_cookiejar.CookieJar类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap