Python http.cookies.SimpleCookie() Examples
The following are 30
code examples of http.cookies.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
http.cookies
, or try the search function
.
Example #1
Source File: test_datasette_auth_github.py From datasette-auth-github with Apache License 2.0 | 6 votes |
def test_auth_callback_calls_github_apis_and_sets_cookie( redirect_path, require_auth_app ): cookie = SimpleCookie() cookie["asgi_auth_redirect"] = redirect_path cookie["asgi_auth_redirect"]["path"] = "/" instance = ApplicationCommunicator( require_auth_app, { "type": "http", "http_version": "1.0", "method": "GET", "path": "/-/auth-callback", "query_string": b"code=github-code-here", "headers": [[b"cookie", cookie.output(header="").lstrip().encode("utf8")]], }, ) await instance.send_input({"type": "http.request"}) output = await instance.receive_output(1) assert_redirects_and_sets_cookie(require_auth_app, output, redirect_path)
Example #2
Source File: common.py From substra-backend with Apache License 2.0 | 6 votes |
def request(self, **kwargs): # create user username = 'substra' password = 'p@$swr0d44' user, created = User.objects.get_or_create(username=username) if created: user.set_password(password) user.save() # simulate login serializer = CustomTokenObtainPairSerializer(data={ 'username': username, 'password': password }) serializer.is_valid() data = serializer.validated_data access_token = str(data.access_token) # simulate right httpOnly cookie and Authorization jwt jwt_auth_header = generate_jwt_auth_header('.'.join(access_token.split('.')[0:2])) self.credentials(HTTP_AUTHORIZATION=jwt_auth_header) self.cookies = SimpleCookie({'signature': access_token.split('.')[2]}) return super().request(**kwargs)
Example #3
Source File: test_sessions.py From quart with MIT License | 6 votes |
def test_secure_cookie_session_interface_save_session() -> None: session = SecureCookieSession() session["something"] = "else" interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = "secret" response = Response("") await interface.save_session(app, session, response) cookies: SimpleCookie = SimpleCookie() cookies.load(response.headers["Set-Cookie"]) cookie = cookies[app.session_cookie_name] assert cookie["path"] == interface.get_cookie_path(app) assert cookie["httponly"] == "" if not interface.get_cookie_httponly(app) else True assert cookie["secure"] == "" if not interface.get_cookie_secure(app) else True if version_info >= (3, 8): assert cookie["samesite"] == (interface.get_cookie_samesite(app) or "") assert cookie["domain"] == (interface.get_cookie_domain(app) or "") assert cookie["expires"] == (interface.get_expiration_time(app, session) or "") assert response.headers["Vary"] == "Cookie"
Example #4
Source File: test_cookies.py From sanic with MIT License | 6 votes |
def test_cookies_asgi(app): @app.route("/") def handler(request): cookie_value = request.cookies["test"] response = text(f"Cookies are: {cookie_value}") response.cookies["right_back"] = "at you" return response request, response = await app.asgi_client.get( "/", 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"
Example #5
Source File: test_http_cookies.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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')
Example #6
Source File: test_cookies.py From sanic with MIT License | 6 votes |
def test_cookie_options(app): @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"] is True
Example #7
Source File: test_cookies.py From sanic with MIT License | 6 votes |
def test_cookie_deletion(app): @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): response.cookies["i_never_existed"]
Example #8
Source File: test_endpoints.py From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_statistics_lazy_cookies(client, site): tag_instant_statistics() tag_lazy_statistics() client.cookies = SimpleCookie({"wtm": ""}) response = client.post( "/wtm/lazy/", json.dumps({}), content_type="application/json" ) data = response.json() assert response.status_code == 200 assert "tags" in data assert len(data["tags"]) == 0 assert "wtm" in response.cookies consent_state = get_consent(response) assert consent_state.get("statistics", "") == "true"
Example #9
Source File: test_http_cookies.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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> """)
Example #10
Source File: tasks.py From doufen with MIT License | 6 votes |
def _frodotk_referer_patch(self): response = self.fetch_url_content('https://m.douban.com/mine/') if not response: raise Exception('服务器无法访问,请稍后重试') set_cookie = response.headers['Set-Cookie'] set_cookie = set_cookie.replace(',', ';') cookie = cookies.SimpleCookie() cookie.load(set_cookie) try: patched_cookie = self._account.session + '; frodotk="{0}"'.format(cookie['frodotk'].value) except KeyError: raise Exception('服务器没有正确授予Cookie,可能是登录会话过期,请重新登录') self._request_session.headers.update({ 'Cookie': patched_cookie, 'Referer': 'https://m.douban.com/', })
Example #11
Source File: test_middleware.py From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_view_necessary(client, site): response = client.get(site.root_page.url) assert response.status_code == 200 tag_instant_necessary(tag_location=Tag.TOP_HEAD) client.cookies = SimpleCookie({"wtm": "necessary:true"}) response = client.get(site.root_page.url) assert response.status_code == 200 assert b'console.log("necessary instant")' in response.content tag_instant_necessary(name="instant necessary 2", tag_location=Tag.BOTTOM_HEAD) client.cookies = SimpleCookie({"wtm": "necessary:true"}) response = client.get(site.root_page.url) assert response.status_code == 200 assert b'console.log("necessary instant")' in response.content client.cookies = SimpleCookie({"wtm": "necessary:false"}) response = client.get(site.root_page.url) assert response.status_code == 200 assert b'console.log("necessary instant")' in response.content
Example #12
Source File: test_http_cookies.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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 = cookies.SimpleCookie() C['val'] = "some,funky;stuff" self.assertEqual(C.output(['val']), 'Set-Cookie: val="some\\054funky\\073stuff"')
Example #13
Source File: bottle.py From lokun-record with GNU Affero General Public License v3.0 | 5 votes |
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 #14
Source File: test_user_login.py From TorCMS with MIT License | 5 votes |
def __init__(self, *rest): self.cookies = cookies.SimpleCookie() AsyncHTTPTestCase.__init__(self, *rest) print("p" * 100)
Example #15
Source File: cli.py From crocoite with MIT License | 5 votes |
def cookie (s): """ argparse: Cookie """ c = SimpleCookie (s) # for some reason the constructor does not raise an exception if the cookie # supplied is invalid. It’ll simply be empty. if len (c) != 1: raise argparse.ArgumentTypeError ('Invalid cookie') # we want a single Morsel return next (iter (c.values ()))
Example #16
Source File: test_controller.py From crocoite with MIT License | 5 votes |
def test_set_cookies (tab, recordingServer): """ Make sure cookies are set properly and only affect the domain they were set for """ logger = Logger () url, reqs = recordingServer cookies = [] c = Morsel () c.set ('foo', 'bar', '') c['domain'] = 'localhost' cookies.append (c) c = Morsel () c.set ('buz', 'beef', '') c['domain'] = 'nonexistent.example' settings = ControllerSettings (idleTimeout=1, timeout=60, cookies=cookies) controller = SinglePageController (url=url, logger=logger, service=Process (), behavior=[], settings=settings) await asyncio.wait_for (controller.run (), settings.timeout*2) assert len (reqs) == 1 req = reqs[0] reqCookies = SimpleCookie (req.headers['cookie']) assert len (reqCookies) == 1 c = next (iter (reqCookies.values ())) assert c.key == cookies[0].key assert c.value == cookies[0].value
Example #17
Source File: bottle.py From aws-servicebroker with Apache License 2.0 | 5 votes |
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: manager.py From pmatic with GNU General Public License v2.0 | 5 votes |
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 #19
Source File: bottle.py From aws-servicebroker with Apache License 2.0 | 5 votes |
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 #20
Source File: test_http_cookies.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_set_secure_httponly_attrs(self): C = cookies.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 #21
Source File: requests.py From kobin with MIT License | 5 votes |
def cookies(self): cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values() return {c.key: c.value for c in cookies}
Example #22
Source File: bottle.py From lokun-record with GNU Affero General Public License v3.0 | 5 votes |
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 #23
Source File: test_i18n.py From zulip with Apache License 2.0 | 5 votes |
def test_cookie(self) -> None: languages = [('en', 'Sign up'), ('de', 'Registrieren'), ('sr', 'Упишите се'), ('zh-hans', '注册'), ] for lang, word in languages: # Applying str function to LANGUAGE_COOKIE_NAME to convert unicode # into an ascii otherwise SimpleCookie will raise an exception self.client.cookies = SimpleCookie({str(settings.LANGUAGE_COOKIE_NAME): lang}) response = self.fetch('get', '/integrations/', 200) self.assert_in_response(word, response)
Example #24
Source File: test_datasette_auth_github.py From datasette-auth-github with Apache License 2.0 | 5 votes |
def test_redirects_to_github_with_asgi_auth_redirect_cookie( path, require_auth_app ): instance = ApplicationCommunicator( require_auth_app, {"type": "http", "http_version": "1.0", "method": "GET", "path": path}, ) await instance.send_input({"type": "http.request"}) output = await instance.receive_output(1) assert "http.response.start" == output["type"] assert 302 == output["status"] headers = tuple([tuple(pair) for pair in output["headers"]]) assert ( b"location", b"https://github.com/login/oauth/authorize?scope=user:email&client_id=x_client_id", ) in headers assert (b"cache-control", b"private") in headers simple_cookie = SimpleCookie() for key, value in headers: if key == b"set-cookie": simple_cookie.load(value.decode("utf8")) assert path == simple_cookie["asgi_auth_redirect"].value assert (await instance.receive_output(1)) == { "type": "http.response.body", "body": b"", }
Example #25
Source File: manager.py From pmatic with GNU General Public License v2.0 | 5 votes |
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 #26
Source File: cookies.py From OpenDoor with GNU General Public License v3.0 | 5 votes |
def _fetch_cookies(self, headers): """ Fetch cookies from response :param dict headers: response header :return: None """ if 'set-cookie' in headers: self._cookies = SimpleCookie(headers['set-cookie'])
Example #27
Source File: session.py From vlcp with Apache License 2.0 | 5 votes |
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 #28
Source File: response.py From ruia with Apache License 2.0 | 5 votes |
def cookies(self) -> dict: if isinstance(self._cookies, SimpleCookie): cur_cookies = {} for key, value in self._cookies.items(): cur_cookies[key] = value.value return cur_cookies else: return self._cookies
Example #29
Source File: _cookiejar.py From deepWordBug with Apache License 2.0 | 5 votes |
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 #30
Source File: _cookiejar.py From deepWordBug with Apache License 2.0 | 5 votes |
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