Python Cookie.SimpleCookie() Examples

The following are 30 code examples of Cookie.SimpleCookie(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Cookie , or try the search function .
Example #1
Source File: bottle.py    From silvia-pi with MIT License 5 votes vote down vote up
def copy(self, cls=None):
        """ Returns a copy of self. """
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            copy._cookies = SimpleCookie()
            copy._cookies.load(self._cookies.output(header=''))
        return copy 
Example #2
Source File: manager.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def _set_cookie(self, name, value):
        cookie = SimpleCookie()
        cookie[name.encode("utf-8")] = value.encode("utf-8")
        self._set_http_header("Set-Cookie", cookie[name.encode("utf-8")].OutputString()) 
Example #3
Source File: bottle.py    From lokun-record with GNU Affero General Public License v3.0 5 votes vote down vote up
def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values()
        if len(cookies) > self.MAX_PARAMS:
            raise HTTPError(413, 'Too many cookies')
        return FormsDict((c.key, c.value) for c in cookies) 
Example #4
Source File: manager.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def _get_auth_cookie_value(self, environ):
        for name, cookie in SimpleCookie(environ.get("HTTP_COOKIE")).items():
            if name == "pmatic_auth":
                return cookie.value 
Example #5
Source File: bottle.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values()
        return FormsDict((c.key, c.value) for c in cookies) 
Example #6
Source File: bottle.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
def copy(self, cls=None):
        ''' Returns a copy of self. '''
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            copy._cookies = SimpleCookie()
            copy._cookies.load(self._cookies.output(header=''))
        return copy 
Example #7
Source File: httputil.py    From pySINDy with MIT License 5 votes vote down vote up
def cookies(self):
        """A dictionary of Cookie.Morsel objects."""
        if not hasattr(self, "_cookies"):
            self._cookies = Cookie.SimpleCookie()
            if "Cookie" in self.headers:
                try:
                    parsed = parse_cookie(self.headers["Cookie"])
                except Exception:
                    pass
                else:
                    for k, v in parsed.items():
                        try:
                            self._cookies[k] = v
                        except Exception:
                            # SimpleCookie imposes some restrictions on keys;
                            # parse_cookie does not. Discard any cookies
                            # with disallowed keys.
                            pass
        return self._cookies 
Example #8
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def COOKIES(self):
        """ Cookie information parsed into a dictionary.

            Secure cookies are NOT decoded automatically. See
            Request.get_cookie() for details.
        """
        if self._COOKIES is None:
            raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
            self._COOKIES = {}
            for cookie in raw_dict.itervalues():
                self._COOKIES[cookie.key] = cookie.value
        return self._COOKIES 
Example #9
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def COOKIES(self):
        """ A dict-like SimpleCookie instance. Use Response.set_cookie() instead. """
        if not self._COOKIES:
            self._COOKIES = SimpleCookie()
        return self._COOKIES 
Example #10
Source File: bottle.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
        cookies = list(cookies.values())[:self.MAX_PARAMS]
        return FormsDict((c.key, c.value) for c in cookies) 
Example #11
Source File: bottle.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def COOKIES(self):
        """ A dict-like SimpleCookie instance. This should not be used directly.
            See :meth:`set_cookie`. """
        depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10
        if not self._cookies:
            self._cookies = SimpleCookie()
        return self._cookies 
Example #12
Source File: bottle.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
        cookies = list(cookies.values())[:self.MAX_PARAMS]
        return FormsDict((c.key, c.value) for c in cookies) 
Example #13
Source File: bottle.py    From appengine-bottle-skeleton with Apache License 2.0 5 votes vote down vote up
def copy(self, cls=None):
        ''' Returns a copy of self. '''
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            copy._cookies = SimpleCookie()
            copy._cookies.load(self._cookies.output())
        return copy 
Example #14
Source File: _cookiejar.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def set(self, set_cookie):
        if set_cookie:
            try:
                simpleCookie = Cookie.SimpleCookie(set_cookie)
            except:
                simpleCookie = Cookie.SimpleCookie(set_cookie.encode('ascii', 'ignore'))

            for k, v in simpleCookie.items():
                domain = v.get("domain")
                if domain:
                    if not domain.startswith("."):
                        domain = "." + domain
                    self.jar[domain.lower()] = simpleCookie 
Example #15
Source File: _cookiejar.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def add(self, set_cookie):
        if set_cookie:
            try:
                simpleCookie = Cookie.SimpleCookie(set_cookie)
            except:
                simpleCookie = Cookie.SimpleCookie(set_cookie.encode('ascii', 'ignore'))

            for k, v in simpleCookie.items():
                domain = v.get("domain")
                if domain:
                    if not domain.startswith("."):
                        domain = "." + domain
                    cookie = self.jar.get(domain) if self.jar.get(domain) else Cookie.SimpleCookie()
                    cookie.update(simpleCookie)
                    self.jar[domain.lower()] = cookie 
Example #16
Source File: session.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def start(self, cookies, cookieopts = None):
        """
        Session start operation. First check among the cookies to find existed sessions;
        if there is not an existed session, create a new one.
        
        :param cookies: cookie header from the client
        
        :param cookieopts: extra options used when creating a new cookie
        
        :return: ``(session_handle, cookies)`` where session_handle is a SessionHandle object,
                 and cookies is a list of created Set-Cookie headers (may be empty)
        """
        c = SimpleCookie(cookies)
        sid = c.get(self.cookiename)
        create = True
        if sid is not None:
            sh = await self.get(sid.value)
            if sh is not None:
                return (self.SessionHandle(sh, self.apiroutine), [])
        if create:
            sh = await self.create()
            m = Morsel()
            m.key = self.cookiename
            m.value = sh.id
            m.coded_value = sh.id
            opts = {'path':'/', 'httponly':True}
            if cookieopts:
                opts.update(cookieopts)
                if not cookieopts['httponly']:
                    del cookieopts['httponly']
            m.update(opts)
            return (sh, [m]) 
Example #17
Source File: bottle.py    From silvia-pi with MIT License 5 votes vote down vote up
def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values()
        return FormsDict((c.key, c.value) for c in cookies) 
Example #18
Source File: proxy.py    From openprocurement.auction with Apache License 2.0 5 votes vote down vote up
def start_response_decorated(start_response_decorated):
    def inner(status, headers):
        headers_obj = IOrderedDict(headers)
        if 'Set-Cookie' in headers_obj and ', ' in headers_obj['Set-Cookie']:
            cookie = SimpleCookie()
            cookie.load(headers_obj['Set-Cookie'])
            del headers_obj['Set-Cookie']
            headers_list = headers_obj.items()
            for key in ("auctions_loggedin", "auction_session"):
                if key in cookie:
                    headers_list += [
                        ('Set-Cookie', cookie[key].output(header="").lstrip().rstrip(','))
                    ]
            headers = headers_list
        return start_response_decorated(status, headers)
    return inner 
Example #19
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_invalid_cookies(self):
        # Accepting these could be a security issue
        C = Cookie.SimpleCookie()
        for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x'):
            C.load(s)
            self.assertEqual(dict(C), {})
            self.assertEqual(C.output(), '') 
Example #20
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_quoted_meta(self):
        # Try cookie with quoted meta-data
        C = Cookie.SimpleCookie()
        C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
        self.assertEqual(C['Customer']['version'], '1')
        self.assertEqual(C['Customer']['path'], '/acme') 
Example #21
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_extra_spaces(self):
        C = Cookie.SimpleCookie()
        C.load('eggs  =  scrambled  ;  secure  ;  path  =  bar   ; foo=foo   ')
        self.assertEqual(C.output(),
            'Set-Cookie: eggs=scrambled; Path=bar; secure\r\nSet-Cookie: foo=foo') 
Example #22
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bad_attrs(self):
        # Issue 16611: make sure we don't break backward compatibility.
        C = Cookie.SimpleCookie()
        C.load('cookie=with; invalid; version; second=cookie;')
        self.assertEqual(C.output(),
            'Set-Cookie: cookie=with\r\nSet-Cookie: second=cookie') 
Example #23
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_secure_httponly_true_if_have_value(self):
        # This isn't really valid, but demonstrates what the current code
        # is expected to do in this case.
        C = Cookie.SimpleCookie()
        C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon')
        self.assertTrue(C['eggs']['httponly'])
        self.assertTrue(C['eggs']['secure'])
        # Here is what it actually does; don't depend on this behavior.  These
        # checks are testing backward compatibility for issue 16611.
        self.assertEqual(C['eggs']['httponly'], 'foo')
        self.assertEqual(C['eggs']['secure'], 'bar') 
Example #24
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_secure_httponly_false_if_not_present(self):
        C = Cookie.SimpleCookie()
        C.load('eggs=scrambled; Path=/bacon')
        self.assertFalse(C['eggs']['httponly'])
        self.assertFalse(C['eggs']['secure']) 
Example #25
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_set_secure_httponly_attrs(self):
        C = Cookie.SimpleCookie('Customer="WILE_E_COYOTE"')
        C['Customer']['secure'] = True
        C['Customer']['httponly'] = True
        self.assertEqual(C.output(),
            'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure') 
Example #26
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_extended_encode(self):
        # Issue 9824: some browsers don't follow the standard; we now
        # encode , and ; to keep them from tripping up.
        C = Cookie.SimpleCookie()
        C['val'] = "some,funky;stuff"
        self.assertEqual(C.output(['val']),
            'Set-Cookie: val="some\\054funky\\073stuff"') 
Example #27
Source File: test_cookie.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_load(self):
        C = Cookie.SimpleCookie()
        C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')

        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
        self.assertEqual(C['Customer']['version'], '1')
        self.assertEqual(C['Customer']['path'], '/acme')

        self.assertEqual(C.output(['path']),
            'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
        self.assertEqual(C.js_output(), r"""
        <script type="text/javascript">
        <!-- begin hiding
        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
        // end hiding -->
        </script>
        """)
        self.assertEqual(C.js_output(['path']), r"""
        <script type="text/javascript">
        <!-- begin hiding
        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
        // end hiding -->
        </script>
        """)

        # loading 'expires'
        C = Cookie.SimpleCookie()
        C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
        self.assertEqual(C['Customer']['expires'],
                         'Wed, 01 Jan 2010 00:00:00 GMT')
        C = Cookie.SimpleCookie()
        C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
        self.assertEqual(C['Customer']['expires'],
                         'Wed, 01 Jan 98 00:00:00 GMT') 
Example #28
Source File: zmqhandlers.py    From Computable with MIT License 5 votes vote down vote up
def _inject_cookie_message(self, msg):
        """Inject the first message, which is the document cookie,
        for authentication."""
        if not PY3 and isinstance(msg, unicode):
            # Cookie constructor doesn't accept unicode strings
            # under Python 2.x for some reason
            msg = msg.encode('utf8', 'replace')
        try:
            identity, msg = msg.split(':', 1)
            self.session.session = cast_unicode(identity, 'ascii')
        except Exception:
            logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
        
        try:
            self.request._cookies = Cookie.SimpleCookie(msg)
        except:
            self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True) 
Example #29
Source File: test_cookie.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_quoted_meta(self):
        # Try cookie with quoted meta-data
        C = Cookie.SimpleCookie()
        C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
        self.assertEqual(C['Customer']['version'], '1')
        self.assertEqual(C['Customer']['path'], '/acme') 
Example #30
Source File: test_cookie.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_extended_encode(self):
        # Issue 9824: some browsers don't follow the standard; we now
        # encode , and ; to keep them from tripping up.
        C = Cookie.SimpleCookie()
        C['val'] = "some,funky;stuff"
        self.assertEqual(C.output(['val']),
            'Set-Cookie: val="some\\054funky\\073stuff"')