Python http.cookies() Examples

The following are 30 code examples of http.cookies(). 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 , or try the search function .
Example #1
Source File: authn.py    From aiocouchdb with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def apply(self, url, headers):
        """Adds cookies to provided ``headers``. If ``headers`` already
        contains any cookies, they would be merged with instance ones.

        :param str url: Request URL
        :param dict headers: Request headers
        """
        if self._cookies is None:
            return

        cookie = http.cookies.SimpleCookie()
        if COOKIE in headers:
            cookie.load(headers.get(COOKIE, ''))
            del headers[COOKIE]

        for name, value in self._cookies.items():
            if isinstance(value, http.cookies.Morsel):
                # use dict method because SimpleCookie class modifies value
                dict.__setitem__(cookie, name, value)
            else:
                cookie[name] = value

        headers[COOKIE] = cookie.output(header='', sep=';').strip() 
Example #2
Source File: request_data.py    From openrasp-iast with Apache License 2.0 6 votes vote down vote up
def get_aiohttp_param(self):
        """
        获取调用aiphttp发送http请求相关方法所需的参数

        Returns:
            dict, 字典形式的参数
        """
        result = {
            "url": self.http_data["url"],
            "headers": self.http_data["headers"],
            "params": self.http_data["params"],
            "cookies": self.http_data["cookies"]
        }
        if self.content_type.startswith("application/json"):
            result["json"] = self.http_data["json"]
        elif self.content_type.startswith("multipart/form-data"):
            result["data"] = self._make_multipart()
            if self.http_data["headers"].get("content-type", None) is not None:
                del result["headers"]["content-type"]
        elif self.http_data["body"] is not None:
            result["data"] = self.http_data["body"]
        else:
            result["data"] = self.http_data["data"]
        return result 
Example #3
Source File: request_data.py    From openrasp-iast with Apache License 2.0 6 votes vote down vote up
def delete_param(self, para_type, para_name):
        """
        删除HTTP请求的某个变量,支持get、post、Cookie、headers

        Parameters:
            para_type - str, 要删除的参数类型,可选get、post、Cookie、headers
            para_name - str, 要删除的参数名
        Raises:
            exceptions.DataParamError - 参数错误引发此异常
        """
        if para_type == "cookies" and para_name in self.http_data["cookies"]:
            del self.http_data["cookies"][para_name]
        elif para_type == "get" and para_name in self.http_data["params"]:
            del self.http_data["params"][para_name]
        elif para_type == "post" and para_name in self.http_data["data"]:
            del self.http_data["data"][para_name]
        elif para_type == "headers" and para_name in self.http_data["headers"]:
            del self.http_data["headers"][para_name]
        else:
            Logger().error("Use an invalid para_type in set_param method!")
            raise exceptions.DataParamError 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # A cookie should not be set.
        self.assertEqual(response.cookies, {})
        # The session is accessed so "Vary: Cookie" should be set.
        self.assertEqual(response['Vary'], 'Cookie') 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_session_delete_on_end(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_httponly_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '')
        self.assertNotIn(
            cookies.Morsel._reserved['httponly'],
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #7
Source File: httputil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def cookies(self) -> Dict[str, http.cookies.Morsel]:
        """A dictionary of ``http.cookies.Morsel`` objects."""
        if not hasattr(self, "_cookies"):
            self._cookies = http.cookies.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: httputil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def cookies(self) -> Dict[str, http.cookies.Morsel]:
        """A dictionary of ``http.cookies.Morsel`` objects."""
        if not hasattr(self, "_cookies"):
            self._cookies = http.cookies.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 #9
Source File: httputil.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def cookies(self) -> Dict[str, http.cookies.Morsel]:
        """A dictionary of ``http.cookies.Morsel`` objects."""
        if not hasattr(self, "_cookies"):
            self._cookies = http.cookies.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 #10
Source File: httputil.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def cookies(self) -> Dict[str, http.cookies.Morsel]:
        """A dictionary of ``http.cookies.Morsel`` objects."""
        if not hasattr(self, "_cookies"):
            self._cookies = http.cookies.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 #11
Source File: request.py    From aiorest with MIT License 5 votes vote down vote up
def cookies(self):
        """Return request cookies.

        A read-only dictionary-like object.
        """
        if self._cookies is None:
            raw = self.headers.get('COOKIE', '')
            parsed = http.cookies.SimpleCookie(raw)
            self._cookies = MultiDictProxy(MultiDict({key: val.value
                                                      for key, val in
                                                      parsed.items()}))
        return self._cookies 
Example #12
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_create_cookie_after_deleting_cookie(self):
        """Setting a cookie after deletion clears the expiry date."""
        response = HttpResponse()
        response.set_cookie('c', 'old-value')
        self.assertEqual(response.cookies['c']['expires'], '')
        response.delete_cookie('c')
        self.assertEqual(response.cookies['c']['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
        response.set_cookie('c', 'new-value')
        self.assertEqual(response.cookies['c']['expires'], '') 
Example #13
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_cookie_secure_prefix(self):
        """
        delete_cookie() sets the secure flag if the cookie name starts with
        __Host- or __Secure- (without that, browsers ignore cookies with those
        prefixes).
        """
        response = HttpResponse()
        for prefix in ('Secure', 'Host'):
            with self.subTest(prefix=prefix):
                cookie_name = '__%s-c' % prefix
                response.delete_cookie(cookie_name)
                self.assertEqual(response.cookies[cookie_name]['secure'], True) 
Example #14
Source File: test_cookiejar.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def testAdd(self):
        cookie_jar = SimpleCookieJar()
        cookie_jar.add("")
        self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b")
        self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; domain=.abc")
        self.assertTrue(".abc" in cookie_jar.jar)

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; domain=abc")
        self.assertTrue(".abc" in cookie_jar.jar)
        self.assertTrue("abc" not in cookie_jar.jar)

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; c=d; domain=abc")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; c=d; domain=abc")
        cookie_jar.add("e=f; domain=abc")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; c=d; domain=abc")
        cookie_jar.add("e=f; domain=.abc")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d; e=f")

        cookie_jar = SimpleCookieJar()
        cookie_jar.add("a=b; c=d; domain=abc")
        cookie_jar.add("e=f; domain=xyz")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
        self.assertEquals(cookie_jar.get("xyz"), "e=f")
        self.assertEquals(cookie_jar.get("something"), "") 
Example #15
Source File: test_cookiejar.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def testSet(self):
        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b")
        self.assertFalse(cookie_jar.jar, "Cookie with no domain should not be added to the jar")

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; domain=.abc")
        self.assertTrue(".abc" in cookie_jar.jar)

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; domain=abc")
        self.assertTrue(".abc" in cookie_jar.jar)
        self.assertTrue("abc" not in cookie_jar.jar)

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; c=d; domain=abc")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; c=d; domain=abc")
        cookie_jar.set("e=f; domain=abc")
        self.assertEquals(cookie_jar.get("abc"), "e=f")

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; c=d; domain=abc")
        cookie_jar.set("e=f; domain=.abc")
        self.assertEquals(cookie_jar.get("abc"), "e=f")

        cookie_jar = SimpleCookieJar()
        cookie_jar.set("a=b; c=d; domain=abc")
        cookie_jar.set("e=f; domain=xyz")
        self.assertEquals(cookie_jar.get("abc"), "a=b; c=d")
        self.assertEquals(cookie_jar.get("xyz"), "e=f")
        self.assertEquals(cookie_jar.get("something"), "") 
Example #16
Source File: request.py    From aiorest with MIT License 5 votes vote down vote up
def __init__(self):
        self.headers = CIMultiDict()
        self._status_code = 200
        self._cookies = http.cookies.SimpleCookie()
        self._deleted_cookies = set() 
Example #17
Source File: request.py    From aiorest with MIT License 5 votes vote down vote up
def cookies(self):
        return self._cookies 
Example #18
Source File: authn.py    From aiocouchdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def apply(self, url, headers):
        """Applies authentication routines on further request. Mostly used
        to set right `Authorization` header or cookies to pass the challenge.

        :param str url: Request URL
        :param dict headers: Request headers
        """
        raise NotImplementedError  # pragma: no cover 
Example #19
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default(self):
        response = HttpResponse()
        response.delete_cookie('c')
        cookie = response.cookies['c']
        self.assertEqual(cookie['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
        self.assertEqual(cookie['max-age'], 0)
        self.assertEqual(cookie['path'], '/')
        self.assertEqual(cookie['secure'], '')
        self.assertEqual(cookie['domain'], '') 
Example #20
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_create_cookie_after_deleting_cookie(self):
        """Setting a cookie after deletion clears the expiry date."""
        response = HttpResponse()
        response.set_cookie('c', 'old-value')
        self.assertEqual(response.cookies['c']['expires'], '')
        response.delete_cookie('c')
        self.assertEqual(response.cookies['c']['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
        response.set_cookie('c', 'new-value')
        self.assertEqual(response.cookies['c']['expires'], '') 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cycle(self):
        """
        This test tested cycle_key() which would create a new session
        key for the same session data. But we can't invalidate previously
        signed cookies (other than letting them expire naturally) so
        testing for this behavior is meaningless.
        """
        pass 
Example #22
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unicode_cookie(self):
        """HttpResponse.set_cookie() works with unicode data."""
        response = HttpResponse()
        cookie_value = '清風'
        response.set_cookie('test', cookie_value)
        self.assertEqual(response.cookies['test'].value, cookie_value) 
Example #23
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain and path looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
        #              Path=/example/
        self.assertEqual(
            'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
            '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #24
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_far_expiration(self):
        """Cookie will expire when a distant expiration time is provided."""
        response = HttpResponse()
        response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
        datetime_cookie = response.cookies['datetime']
        self.assertIn(
            datetime_cookie['expires'],
            # assertIn accounts for slight time dependency (#23450)
            ('Sat, 01 Jan 2028 04:05:06 GMT', 'Sat, 01 Jan 2028 04:05:07 GMT')
        ) 
Example #25
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_max_age_expiration(self):
        """Cookie will expire if max_age is provided."""
        response = HttpResponse()
        set_cookie_time = time.time()
        with freeze_time(set_cookie_time):
            response.set_cookie('max_age', max_age=10)
        max_age_cookie = response.cookies['max_age']
        self.assertEqual(max_age_cookie['max-age'], 10)
        self.assertEqual(max_age_cookie['expires'], http_date(set_cookie_time + 10)) 
Example #26
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_samesite_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse()
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session['hello'] = 'world'
        response = middleware.process_response(request, response)
        self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict') 
Example #27
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_secure_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True) 
Example #28
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_cookie_secure_prefix(self):
        """
        delete_cookie() sets the secure flag if the cookie name starts with
        __Host- or __Secure- (without that, browsers ignore cookies with those
        prefixes).
        """
        response = HttpResponse()
        for prefix in ('Secure', 'Host'):
            with self.subTest(prefix=prefix):
                cookie_name = '__%s-c' % prefix
                response.delete_cookie(cookie_name)
                self.assertEqual(response.cookies[cookie_name]['secure'], True) 
Example #29
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default(self):
        response = HttpResponse()
        response.delete_cookie('c')
        cookie = response.cookies['c']
        self.assertEqual(cookie['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
        self.assertEqual(cookie['max-age'], 0)
        self.assertEqual(cookie['path'], '/')
        self.assertEqual(cookie['secure'], '')
        self.assertEqual(cookie['domain'], '') 
Example #30
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_samesite(self):
        response = HttpResponse()
        response.set_cookie('example', samesite='Lax')
        self.assertEqual(response.cookies['example']['samesite'], 'Lax')
        response.set_cookie('example', samesite='strict')
        self.assertEqual(response.cookies['example']['samesite'], 'strict')