Python Cookie 模块,CookieError() 实例源码

我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用Cookie.CookieError()

项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def get_user_info(http_cookie, cookie_name=_COOKIE_NAME):
  """Gets the requestor's user info from an HTTP Cookie header.

  Args:
    http_cookie: The value of the 'Cookie' HTTP request header.
    cookie_name: The name of the cookie that stores the user info.

  Returns:
    A tuple (email, admin, user_id) where:
      email: The user's email address, if any.
      admin: True if the user is an admin; False otherwise.
      user_id: The user ID, if any.
  """
  try:
    cookie = Cookie.SimpleCookie(http_cookie)
  except Cookie.CookieError:
    return '', False, ''

  cookie_dict = dict((k, v.value) for k, v in cookie.iteritems())
  return _get_user_info_from_dict(cookie_dict, cookie_name)
项目:fortiosclient    作者:jerryz1982    | 项目源码 | 文件源码
def format_cookie(cookie):
        if not cookie:
            return None
        try:
            fmt_headers = {}
            cookies = Cookie.SimpleCookie(cookie)
            for key, morsel in six.iteritems(cookies):
                if "ccsrftoken" in morsel.key:
                    morsel.coded_value = morsel.value
                    fmt_headers["X-CSRFTOKEN"] = morsel.value
                    break
            fmt_headers["Cookie"] = cookies.output(header="").lstrip()
            return fmt_headers
        except (Cookie.CookieError, KeyError):
            LOG.error(_LE("The cookie ccsrftoken cannot be formatted"))
            raise Cookie.CookieError
项目:web3py    作者:web2py    | 项目源码 | 文件源码
def parse_cookies(environ):
    cookies = Cookie.SimpleCookie() 
    env_cookie = environ.get('HTTP_COOKIE','')
    if env_cookie:
        for single_cookie in env_cookie.split(';'):
            single_cookie = single_cookie.strip()
            if single_cookie:
                try:
                    cookies.load(single_cookie)
                except Cookie.CookieError:
                    pass  # single invalid cookie ignore
    return cookies
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def __init__(self, request, id=None, invalidate_corrupt=False,
                 use_cookies=True, type=None, data_dir=None,
                 key='beaker.session.id', timeout=None, cookie_expires=True,
                 cookie_domain=None, secret=None, secure=False,
                 namespace_class=None, **namespace_args):
        if not type:
            if data_dir:
                self.type = 'file'
            else:
                self.type = 'memory'
        else:
            self.type = type

        self.namespace_class = namespace_class or clsmap[self.type]

        self.namespace_args = namespace_args

        self.request = request
        self.data_dir = data_dir
        self.key = key

        self.timeout = timeout
        self.use_cookies = use_cookies
        self.cookie_expires = cookie_expires

        # Default cookie domain/path
        self._domain = cookie_domain
        self._path = '/'
        self.was_invalidated = False
        self.secret = secret
        self.secure = secure
        self.id = id
        self.accessed_dict = {}

        if self.use_cookies:
            cookieheader = request.get('cookie', '')
            if secret:
                try:
                    self.cookie = SignedCookie(secret, input=cookieheader)
                except Cookie.CookieError:
                    self.cookie = SignedCookie(secret, input=None)
            else:
                self.cookie = Cookie.SimpleCookie(input=cookieheader)

            if not self.id and self.key in self.cookie:
                self.id = self.cookie[self.key].value

        self.is_new = self.id is None
        if self.is_new:
            self._create_id()
            self['_accessed_time'] = self['_creation_time'] = time.time()
        else:
            try:
                self.load()
            except:
                if invalidate_corrupt:
                    self.invalidate()
                else:
                    raise
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def __init__(self, request, key='beaker.session.id', timeout=None,
                 cookie_expires=True, cookie_domain=None, encrypt_key=None,
                 validate_key=None, secure=False, **kwargs):

        if not crypto.has_aes and encrypt_key:
            raise InvalidCryptoBackendError("No AES library is installed, can't generate "
                                  "encrypted cookie-only Session.")

        self.request = request
        self.key = key
        self.timeout = timeout
        self.cookie_expires = cookie_expires
        self.encrypt_key = encrypt_key
        self.validate_key = validate_key
        self.request['set_cookie'] = False
        self.secure = secure
        self._domain = cookie_domain
        self._path = '/'

        try:
            cookieheader = request['cookie']
        except KeyError:
            cookieheader = ''

        if validate_key is None:
            raise BeakerException("No validate_key specified for Cookie only "
                                  "Session.")

        try:
            self.cookie = SignedCookie(validate_key, input=cookieheader)
        except Cookie.CookieError:
            self.cookie = SignedCookie(validate_key, input=None)

        self['_id'] = self._make_id()
        self.is_new = True

        # If we have a cookie, load it
        if self.key in self.cookie and self.cookie[self.key].value is not None:
            self.is_new = False
            try:
                self.update(self._decrypt_data())
            except:
                pass
            if self.timeout is not None and time.time() - \
               self['_accessed_time'] > self.timeout:
                self.clear()
            self.accessed_dict = self.copy()
            self._create_cookie()
项目:py-script    作者:xiaoxiamin    | 项目源码 | 文件源码
def parse_cookies(http_cookie):
    r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values.

    >>> sorted(parse_cookies('').items())
    []
    >>> sorted(parse_cookies('a=1').items())
    [('a', '1')]
    >>> sorted(parse_cookies('a=1%202').items())
    [('a', '1 2')]
    >>> sorted(parse_cookies('a=Z%C3%A9Z').items())
    [('a', 'Z\xc3\xa9Z')]
    >>> sorted(parse_cookies('a=1; b=2; c=3').items())
    [('a', '1'), ('b', '2'), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items())
    [('a', '1'), ('b', 'w('), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items())
    [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')]

    >>> sorted(parse_cookies('keebler=E=mc2').items())
    [('keebler', 'E=mc2')]
    >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items())
    [('keebler', 'E=mc2; L="Loves"; fudge=\n;')]
    """
    #print "parse_cookies"
    if '"' in http_cookie:
        # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing
        cookie = Cookie.SimpleCookie()
        try:
            cookie.load(http_cookie)
        except Cookie.CookieError:
            # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by
            # first splitting on ';' and loading each attr=value pair separately
            cookie = Cookie.SimpleCookie()
            for attr_value in http_cookie.split(';'):
                try:
                    cookie.load(attr_value)
                except Cookie.CookieError:
                    pass
        cookies = dict((k, urllib.unquote(v.value)) for k, v in cookie.iteritems())
    else:
        # HTTP_COOKIE doesn't have quotes, use fast cookie parsing
        cookies = {}
        for key_value in http_cookie.split(';'):
            key_value = key_value.split('=', 1)
            if len(key_value) == 2:
                key, value = key_value
                cookies[key.strip()] = urllib.unquote(value.strip())
    return cookies
项目:py-script    作者:xiaoxiamin    | 项目源码 | 文件源码
def parse_cookies(http_cookie):
    r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values.

    >>> sorted(parse_cookies('').items())
    []
    >>> sorted(parse_cookies('a=1').items())
    [('a', '1')]
    >>> sorted(parse_cookies('a=1%202').items())
    [('a', '1 2')]
    >>> sorted(parse_cookies('a=Z%C3%A9Z').items())
    [('a', 'Z\xc3\xa9Z')]
    >>> sorted(parse_cookies('a=1; b=2; c=3').items())
    [('a', '1'), ('b', '2'), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items())
    [('a', '1'), ('b', 'w('), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items())
    [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')]

    >>> sorted(parse_cookies('keebler=E=mc2').items())
    [('keebler', 'E=mc2')]
    >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items())
    [('keebler', 'E=mc2; L="Loves"; fudge=\n;')]
    """
    #print "parse_cookies"
    if '"' in http_cookie:
        # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing
        cookie = Cookie.SimpleCookie()
        try:
            cookie.load(http_cookie)
        except Cookie.CookieError:
            # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by
            # first splitting on ';' and loading each attr=value pair separately
            cookie = Cookie.SimpleCookie()
            for attr_value in http_cookie.split(';'):
                try:
                    cookie.load(attr_value)
                except Cookie.CookieError:
                    pass
        cookies = dict((k, urllib.unquote(v.value)) for k, v in cookie.iteritems())
    else:
        # HTTP_COOKIE doesn't have quotes, use fast cookie parsing
        cookies = {}
        for key_value in http_cookie.split(';'):
            key_value = key_value.split('=', 1)
            if len(key_value) == 2:
                key, value = key_value
                cookies[key.strip()] = urllib.unquote(value.strip())
    return cookies
项目:deb-python-autobahn    作者:openstack    | 项目源码 | 文件源码
def onConnect(self, request):

        # This is called during the initial WebSocket opening handshake.

        protocol, headers = None, {}

        # our cookie tracking ID
        self._cbtid = None

        # see if there already is a cookie set ..
        if 'cookie' in request.headers:
            try:
                cookie = Cookie.SimpleCookie()
                cookie.load(str(request.headers['cookie']))
            except Cookie.CookieError:
                pass
            else:
                if 'cbtid' in cookie:
                    cbtid = cookie['cbtid'].value
                    if cbtid in self.factory._cookies:
                        self._cbtid = cbtid
                        log.msg("Cookie already set: %s" % self._cbtid)

        # if no cookie is set, create a new one ..
        if self._cbtid is None:

            self._cbtid = newid()
            maxAge = 86400

            cbtData = {'created': utcnow(),
                       'authenticated': None,
                       'maxAge': maxAge,
                       'connections': set()}

            self.factory._cookies[self._cbtid] = cbtData

            # do NOT add the "secure" cookie attribute! "secure" refers to the
            # scheme of the Web page that triggered the WS, not WS itself!!
            ##
            headers['Set-Cookie'] = 'cbtid=%s;max-age=%d' % (self._cbtid, maxAge)
            log.msg("Setting new cookie: %s" % self._cbtid)

        # add this WebSocket connection to the set of connections
        # associated with the same cookie
        self.factory._cookies[self._cbtid]['connections'].add(self)

        # accept the WebSocket connection, speaking subprotocol `protocol`
        # and setting HTTP headers `headers`
        return (protocol, headers)
项目:cosa-nostra    作者:joxeankoret    | 项目源码 | 文件源码
def parse_cookies(http_cookie):
    r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values.

    >>> sorted(parse_cookies('').items())
    []
    >>> sorted(parse_cookies('a=1').items())
    [('a', '1')]
    >>> sorted(parse_cookies('a=1%202').items())
    [('a', '1 2')]
    >>> sorted(parse_cookies('a=Z%C3%A9Z').items())
    [('a', 'Z\xc3\xa9Z')]
    >>> sorted(parse_cookies('a=1; b=2; c=3').items())
    [('a', '1'), ('b', '2'), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items())
    [('a', '1'), ('b', 'w('), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items())
    [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')]

    >>> sorted(parse_cookies('keebler=E=mc2').items())
    [('keebler', 'E=mc2')]
    >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items())
    [('keebler', 'E=mc2; L="Loves"; fudge=\n;')]
    """
    #print "parse_cookies"
    if '"' in http_cookie:
        # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing
        cookie = Cookie.SimpleCookie()
        try:
            cookie.load(http_cookie)
        except Cookie.CookieError:
            # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by
            # first splitting on ';' and loading each attr=value pair separately
            cookie = Cookie.SimpleCookie()
            for attr_value in http_cookie.split(';'):
                try:
                    cookie.load(attr_value)
                except Cookie.CookieError:
                    pass
        cookies = dict((k, urllib.unquote(v.value)) for k, v in cookie.iteritems())
    else:
        # HTTP_COOKIE doesn't have quotes, use fast cookie parsing
        cookies = {}
        for key_value in http_cookie.split(';'):
            key_value = key_value.split('=', 1)
            if len(key_value) == 2:
                key, value = key_value
                cookies[key.strip()] = urllib.unquote(value.strip())
    return cookies