我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用http.cookies.SimpleCookie()。
def test_cookie_options(): app = Sanic('test_text') @app.route('/') def handler(request): response = text("OK") response.cookies['test'] = 'at you' response.cookies['test']['httponly'] = True response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10) return response request, response = sanic_endpoint_test(app) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response_cookies['test'].value == 'at you' assert response_cookies['test']['httponly'] == True
def async_good(request): """Good page handler.""" global db global jinja data = { "title": "Top of the best stikers for Telegram", "active_good": "class=\"active\"", "active_bad": "", "top": {} } session = await session_handler(request=request) cookies_for_responce = SimpleCookie() cookies_for_responce['new'] = session['new'] cookies_for_responce['stickers'] = session['stickers'] data["top"] = await db.get_top(12, 'ITERATOR_LE') text = jinja.get_template('good.html').render( title=data["title"], active_good=data["active_good"], active_bad=data["active_bad"], top=data["top"] ) return request.Response( text=text, mime_type='text/html', cookies=cookies_for_responce)
def action_bad(request): """Bad page handler.""" global db global jinja data = { "title": "Top of bad stikers for Telegram", "active_good": "", "active_bad": "class=\"active\"", "top": {} } session = await session_handler(request=request) cookies_for_responce = SimpleCookie() cookies_for_responce['new'] = session['new'] cookies_for_responce['stickers'] = session['stickers'] data["top"] = await db.get_top(9, 'ITERATOR_GE') text = jinja.get_template('good.html').render( title=data["title"], active_good=data["active_good"], active_bad=data["active_bad"], top=data["top"] ) return request.Response( text=text, mime_type='text/html', cookies=cookies_for_responce)
def test_load(self): C = cookies.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> """)
def _load_cookie(self): """Loads HTTP Cookie from environ""" cookie = SimpleCookie(self._environ.get('HTTP_COOKIE')) vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name] # no session was started yet if not vishnu_keys: return morsel = cookie[vishnu_keys[0]] morsel_value = morsel.value if self._config.encrypt_key: cipher = AESCipher(self._config.encrypt_key) morsel_value = cipher.decrypt(morsel_value) received_sid = Session.decode_sid(self._config.secret, morsel_value) if received_sid: self._sid = received_sid else: logging.warn("found cookie with invalid signature")
def test_cookie_options(): app = Sanic('test_text') @app.route('/') def handler(request): response = text("OK") response.cookies['test'] = 'at you' response.cookies['test']['httponly'] = True response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10) return response request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response_cookies['test'].value == 'at you' assert response_cookies['test']['httponly'] == True
def test_cookie_deletion(): app = Sanic('test_text') @app.route('/') def handler(request): response = text("OK") del response.cookies['i_want_to_die'] response.cookies['i_never_existed'] = 'testing' del response.cookies['i_never_existed'] return response request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert int(response_cookies['i_want_to_die']['max-age']) == 0 with pytest.raises(KeyError): hold_my_beer = response.cookies['i_never_existed']
def test_special_attrs(self): # 'expires' C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['expires'] = 0 # can't test exact output, it always depends on current date/time self.assertTrue(C.output().endswith('GMT')) # loading 'expires' C = cookies.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 = cookies.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') # 'max-age' C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"') C['Customer']['max-age'] = 10 self.assertEqual(C.output(), 'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
def __init__(self, body, headers, status_code, status_phrase, cookies=None, content_type=None, charset=None): assert is_async_generator(body) or isinstance(body, (str, bytes)), ( 'body must be str or bytes or async generator, got: %s' % ( type(body), ) ) assert isinstance(headers, QueryList), ( 'header must be a QueryList object' ) assert isinstance(status_code, int) assert isinstance(status_phrase, str) self.body = body self.headers = headers self.status_code = status_code self.status_phrase = status_phrase self.content_type = content_type or DEFAULT_CONTENT_TYPE self.charset = charset or DEFAULT_CHARSET self.cookies = SimpleCookie(cookies)
def _session_cookie(self,forcenew=False): cookiestring = "\n".join(self.headers.get_all('Cookie',failobj=[])) c = cookie() c.load(cookiestring) try: if forcenew or self.sessioncookies[c['session_id'].value]-time() > 3600: raise ValueError('new cookie needed') except: c['session_id']=uuid().hex for m in c: if m=='session_id': self.sessioncookies[c[m].value] = time() c[m]["httponly"] = True c[m]["max-age"] = 3600 c[m]["expires"] = self.date_time_string(time()+3600) self.sessionidmorsel = c[m] break
def test_cookie(self): response, content = self.assert_get('/') cookies_ = cookies.SimpleCookie(response['set-cookie']) self.assertEqual(cookies_['test-cookie'].value, '1') self.assertIn('dummy-cookie', cookies_) response, content = self.assert_get('/', cookies=cookies_) cookies_ = cookies.SimpleCookie(response['set-cookie']) self.assertEqual(cookies_['test-cookie'].value, '2') self.assertIn('dummy-cookie', cookies_) response, content = self.assert_get('/secure') cookies_ = cookies.SimpleCookie(response['set-cookie']) self.assertNotIn('dummy-cookie1', cookies_) self.assertNotIn('dummy-cookie2', cookies_) self.assertNotIn('dummy-cookie3', cookies_) # response, content = self.assert_get('/clear') cookies_ = cookies.SimpleCookie(response['set-cookie']) self.assertIn('dummy-cookie', cookies_) self.assertEqual(cookies_['dummy-cookie']['expires'], 'Sat, 01 Jan 2000 00:00:01 GMT') self.assertEqual(cookies_['dummy-cookie'].value, '')
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
def __init__(self, *, status=200, reason=None, headers=None): self._body = None self._keep_alive = None self._chunked = False self._chunk_size = None self._compression = False self._compression_force = False self._headers = CIMultiDict() self._cookies = SimpleCookie() self._req = None self._resp_impl = None self._eof_sent = False self._task = None if headers is not None: # TODO: optimize CIMultiDict extending self._headers.extend(headers) self._headers.setdefault(hdrs.CONTENT_TYPE, 'application/octet-stream') self.set_status(status, reason)
def do_POST(self): # How long was the post data? length = int(self.headers.get('Content-length', 0)) # Read and parse the post data data = self.rfile.read(length).decode() yourname = parse_qs(data)["yourname"][0] # Create cookie. c = cookies.SimpleCookie() # 1. Set the fields of the cookie. # Give the cookie a value from the 'yourname' variable, # a domain (localhost), and a max-age. # Send a 303 back to the root page, with a cookie! self.send_response(303) # redirect via GET self.send_header('Location', '/') self.send_header('Set-Cookie', c['yourname'].OutputString()) self.end_headers()
def do_POST(self): # How long was the post data? length = int(self.headers.get('Content-length', 0)) # Read and parse the post data data = self.rfile.read(length).decode() yourname = parse_qs(data)["yourname"][0] # Create cookie. c = cookies.SimpleCookie() c['yourname'] = yourname c['yourname']['domain'] = 'localhost' c['yourname']['max-age'] = 60 # Send a 303 back to the root page, with a cookie! self.send_response(303) # redirect via GET self.send_header('Location', '/') self.send_header('Set-Cookie', c['yourname'].OutputString()) self.end_headers()
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
def test_cookie_options(): app = Mach9('test_text') @app.route('/') def handler(request): response = text("OK") response.cookies['test'] = 'at you' response.cookies['test']['httponly'] = True response.cookies['test']['expires'] = datetime.now() + timedelta(seconds=10) return response request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response_cookies['test'].value == 'at you' assert response_cookies['test']['httponly'] == True
def test_cookie_deletion(): app = Mach9('test_text') @app.route('/') def handler(request): response = text("OK") del response.cookies['i_want_to_die'] response.cookies['i_never_existed'] = 'testing' del response.cookies['i_never_existed'] return response request, response = app.test_client.get('/') response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert int(response_cookies['i_want_to_die']['max-age']) == 0 with pytest.raises(KeyError): hold_my_beer = response.cookies['i_never_existed']
def setCookie(self, cookie): c = cookies.SimpleCookie() c.load(cookie) if 'z_c0' not in c: raise Exception('Invalid cookie: ' 'no authorization (z_c0) in cookie') if '_xsrf' not in c: raise Exception('Invalid cookie: no _xsrf in cookie') self.headers['Cookie'] = cookie.strip() self.headers['Authorization'] = 'Bearer %s' % c['z_c0'].value self._xsrf = c['_xsrf'].value
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)
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
def set_cookies(self, name, value, ttl=12 * 35 * 24 * 60 * 60, path='/'): """ :param ttl: cookie????, ? :type ttl: int :type path: str :type name: str :type value: str """ from http.cookies import SimpleCookie c = SimpleCookie() c[name] = value c[name]["path"] = path c[name]["expires"] = ttl self.extra_cookies[name] = c[name].OutputString()
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)
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
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
def test_cookies(): app = Sanic('test_text') @app.route('/') def handler(request): response = text('Cookies are: {}'.format(request.cookies['test'])) response.cookies['right_back'] = 'at you' return response request, response = sanic_endpoint_test(app, cookies={"test": "working!"}) response_cookies = SimpleCookie() response_cookies.load(response.headers.get('Set-Cookie', {})) assert response.text == 'Cookies are: working!' assert response_cookies['right_back'].value == 'at you'
def cookies(self): if self._cookies is None: # # ?? HTTP ???, ?? cookie ?? # cookie = self.headers.get('Cookie') or self.headers.get('cookie') if cookie is not None: cookies = SimpleCookie() cookies.load(cookie) # ??cookie self._cookies = {name: cookie.value for name, cookie in cookies.items()} else: self._cookies = {} return self._cookies
def test_unsubscribe_api_failure( mock_unsubscribe, api_response_400, logged_in_client ): logged_in_client.cookies = SimpleCookie( {settings.SSO_PROXY_SESSION_COOKIE: 1} ) mock_unsubscribe.return_value = api_response_400 response = logged_in_client.post(reverse('unsubscribe')) mock_unsubscribe.assert_called_once_with(sso_session_id='213') view = views.EmailUnsubscribeView assert response.status_code == http.client.OK assert response.template_name == view.failure_template
def make_request_headers(self, method, host, headers, cookies): _headers = [] if not headers.get('host'): _headers.append('Host: ' + host + (':443' if method.lower() == 'connect' else '')) if method.lower() == 'post' and not self.data: _headers.append('Content-Length: 0') if self.data: data = self.make_request_data(self.data) _headers.append('Content-Length: {}'.format(len(data.encode('utf-8')))) if isinstance(self.data, dict) and not headers.get('Content-Type'): _headers.append('Content-Type: application/x-www-form-urlencoded') # add cookies if cookies: if isinstance(cookies, (DictCookie, SimpleCookie)): _cookies = [] for k in cookies: # TODO, path ? if isinstance(cookies[k], Morsel): v = cookies[k].value else: v = cookies[k] _cookies.append('{}={};'.format(k, v)) cookie = 'Cookie: ' + ' '.join(_cookies) _headers.append(cookie) elif isinstance(cookies, dict): _cookies = [] for k, v in cookies.items(): _cookies.append('{}={};'.format(k, v)) cookie = 'Cookie: ' + ' '.join(_cookies) _headers.append(cookie) # make headers for k, v in headers.items(): _headers.append(k + ': ' + v) return '\r\n'.join(_headers)
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
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)
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