当前位置: 首页>>代码示例>>Python>>正文


Python cookies.Morsel方法代码示例

本文整理汇总了Python中http.cookies.Morsel方法的典型用法代码示例。如果您正苦于以下问题:Python cookies.Morsel方法的具体用法?Python cookies.Morsel怎么用?Python cookies.Morsel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在http.cookies的用法示例。


在下文中一共展示了cookies.Morsel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cookies

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
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 
开发者ID:tp4a,项目名称:teleport,代码行数:21,代码来源:httputil.py

示例2: setcookie

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False):
        """
        Add a new cookie
        """
        newcookie = Morsel()
        newcookie.key = key
        newcookie.value = value
        newcookie.coded_value = value
        if max_age is not None:
            newcookie['max-age'] = max_age
        if expires is not None:
            newcookie['expires'] = expires
        if path is not None:
            newcookie['path'] = path
        if domain is not None:
            newcookie['domain'] = domain
        if secure:
            newcookie['secure'] = secure
        if httponly:
            newcookie['httponly'] = httponly
        self.sent_cookies = [c for c in self.sent_cookies if c.key != key]
        self.sent_cookies.append(newcookie) 
开发者ID:hubo1016,项目名称:vlcp,代码行数:24,代码来源:http.py

示例3: destroy

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def destroy(self, sessionid):
        """
        Destroy a session
        
        :param sessionid: session ID
        
        :return: a list of Set-Cookie headers to be sent to the client
        """
        await call_api(self.apiroutine, 'memorystorage', 'delete', {'key': __name__ + '.' + sessionid})
        m = Morsel()
        m.key = self.cookiename
        m.value = 'deleted'
        m.coded_value = 'deleted'
        opts = {'path':'/', 'httponly':True, 'max-age':0}
        m.update(opts)
        return [m] 
开发者ID:hubo1016,项目名称:vlcp,代码行数:18,代码来源:session.py

示例4: setcookie

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def setcookie(name, value, expires='', domain=None,
              secure=False, httponly=False, path=None):
    """Sets a cookie."""
    morsel = Morsel()
    name, value = safestr(name), safestr(value)
    morsel.set(name, value, quote(value))
    if isinstance(expires, int) and expires < 0:
        expires = -1000000000
    morsel['expires'] = expires
    morsel['path'] = path or ctx.homepath+'/'
    if domain:
        morsel['domain'] = domain
    if secure:
        morsel['secure'] = secure
    value = morsel.OutputString()
    if httponly:
        value += '; httponly'
    header('Set-Cookie', value) 
开发者ID:Naayouu,项目名称:Hatkey,代码行数:20,代码来源:webapi.py

示例5: toCookieParam

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def toCookieParam (m):
    """
    Convert Python’s http.cookies.Morsel to Chrome’s CookieParam, see
    https://chromedevtools.github.io/devtools-protocol/1-3/Network#type-CookieParam
    """

    assert isinstance (m, Morsel)

    out = {'name': m.key, 'value': m.value}

    # unsupported by chrome
    for k in ('max-age', 'comment', 'version'):
        if m[k]:
            raise ValueError (f'Unsupported cookie attribute {k} set, cannot convert')

    for mname, cname in [('expires', None), ('path', None), ('domain', None), ('secure', None), ('httponly', 'httpOnly')]:
        value = m[mname]
        if value:
            cname = cname or mname
            out[cname] = value

    return out 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:24,代码来源:devtools.py

示例6: test_setdefault

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_setdefault(self):
        morsel = cookies.Morsel()
        morsel.update({
            'domain': 'example.com',
            'version': 2,
        })
        # this shouldn't override the default value
        self.assertEqual(morsel.setdefault('expires', 'value'), '')
        self.assertEqual(morsel['expires'], '')
        self.assertEqual(morsel.setdefault('Version', 1), 2)
        self.assertEqual(morsel['version'], 2)
        self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com')
        self.assertEqual(morsel['domain'], 'example.com')

        with self.assertRaises(cookies.CookieError):
            morsel.setdefault('invalid', 'value')
        self.assertNotIn('invalid', morsel) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_http_cookies.py

示例7: update_cookies

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
        """Update request cookies header."""
        if not cookies:
            return

        c = SimpleCookie()
        if hdrs.COOKIE in self.headers:
            c.load(self.headers.get(hdrs.COOKIE, ''))
            del self.headers[hdrs.COOKIE]

        if isinstance(cookies, Mapping):
            iter_cookies = cookies.items()
        else:
            iter_cookies = cookies  # type: ignore
        for name, value in iter_cookies:
            if isinstance(value, Morsel):
                # Preserve coded_value
                mrsl_val = value.get(value.key, Morsel())
                mrsl_val.set(value.key, value.value, value.coded_value)  # type: ignore  # noqa
                c[name] = mrsl_val
            else:
                c[name] = value  # type: ignore

        self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip() 
开发者ID:TouwaStar,项目名称:Galaxy_Plugin_Bethesda,代码行数:26,代码来源:client_reqrep.py

示例8: update_cookies

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def update_cookies(self, cookies):
        """Update request cookies header."""
        if not cookies:
            return

        c = SimpleCookie()
        if hdrs.COOKIE in self.headers:
            c.load(self.headers.get(hdrs.COOKIE, ''))
            del self.headers[hdrs.COOKIE]

        for name, value in cookies.items():
            if isinstance(value, Morsel):
                # Preserve coded_value
                mrsl_val = value.get(value.key, Morsel())
                mrsl_val.set(value.key, value.value, value.coded_value)
                c[name] = mrsl_val
            else:
                c[name] = value

        self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip() 
开发者ID:skylander86,项目名称:lambda-text-extractor,代码行数:22,代码来源:client_reqrep.py

示例9: cookies

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def cookies(self) -> Dict[str, http.cookies.Morsel]:
        """An alias for
        `self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
        return self.request.cookies 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:6,代码来源:web.py

示例10: __setitem__

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def __setitem__(self, key, value):
            if isinstance(value, Morsel):
                # allow assignment of constructed Morsels (e.g. for pickling)
                dict.__setitem__(self, key, value)
            else:
                super().__setitem__(key, value) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:8,代码来源:cookie.py

示例11: start

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
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]) 
开发者ID:hubo1016,项目名称:vlcp,代码行数:34,代码来源:session.py

示例12: test_set_cookies

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
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 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:31,代码来源:test_controller.py

示例13: test_defaults

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_defaults(self):
        morsel = cookies.Morsel()
        self.assertIsNone(morsel.key)
        self.assertIsNone(morsel.value)
        self.assertIsNone(morsel.coded_value)
        self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys())
        for key, val in morsel.items():
            self.assertEqual(val, '', key) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:10,代码来源:test_http_cookies.py

示例14: test_reserved_keys

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_reserved_keys(self):
        M = cookies.Morsel()
        # tests valid and invalid reserved keys for Morsels
        for i in M._reserved:
            # Test that all valid keys are reported as reserved and set them
            self.assertTrue(M.isReservedKey(i))
            M[i] = '%s_value' % i
        for i in M._reserved:
            # Test that valid key values come out fine
            self.assertEqual(M[i], '%s_value' % i)
        for i in "the holy hand grenade".split():
            # Test that invalid keys raise CookieError
            self.assertRaises(cookies.CookieError,
                              M.__setitem__, i, '%s_value' % i) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:16,代码来源:test_http_cookies.py

示例15: test_setter

# 需要导入模块: from http import cookies [as 别名]
# 或者: from http.cookies import Morsel [as 别名]
def test_setter(self):
        M = cookies.Morsel()
        # tests the .set method to set keys and their values
        for i in M._reserved:
            # Makes sure that all reserved keys can't be set this way
            self.assertRaises(cookies.CookieError,
                              M.set, i, '%s_value' % i, '%s_value' % i)
        for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
            # Try typical use case. Setting decent values.
            # Check output and js_output.
            M['path'] = '/foo' # Try a reserved key as well
            M.set(i, "%s_val" % i, "%s_coded_val" % i)
            self.assertEqual(
                M.output(),
                "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
            expected_js_output = """
        <script type="text/javascript">
        <!-- begin hiding
        document.cookie = "%s=%s; Path=/foo";
        // end hiding -->
        </script>
        """ % (i, "%s_coded_val" % i)
            self.assertEqual(M.js_output(), expected_js_output)
        for i in ["foo bar", "foo@bar"]:
            # Try some illegal characters
            self.assertRaises(cookies.CookieError,
                              M.set, i, '%s_value' % i, '%s_value' % i) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:29,代码来源:test_http_cookies.py


注:本文中的http.cookies.Morsel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。