Python mechanize 模块,Cookie() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用mechanize.Cookie()

项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def domain_return_ok(self, domain, request):
        """Return false if cookies should not be returned, given cookie domain.

        This is here as an optimization, to remove the need for checking every
        cookie with a particular domain (which may involve reading many files).
        The default implementations of domain_return_ok and path_return_ok
        (return True) leave all the work to return_ok.

        If domain_return_ok returns true for the cookie domain, path_return_ok
        is called for the cookie path.  Otherwise, path_return_ok and return_ok
        are never called for that cookie domain.  If path_return_ok returns
        true, return_ok is called with the Cookie object itself for a full
        check.  Otherwise, return_ok is never called for that cookie path.

        Note that domain_return_ok is called for every *cookie* domain, not
        just for the *request* domain.  For example, the function might be
        called with both ".acme.com" and "www.acme.com" if the request domain
        is "www.acme.com".  The same goes for path_return_ok.

        For argument documentation, see the docstring for return_ok.

        """
        return True
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def domain_return_ok(self, domain, request):
        """Return false if cookies should not be returned, given cookie domain.

        This is here as an optimization, to remove the need for checking every
        cookie with a particular domain (which may involve reading many files).
        The default implementations of domain_return_ok and path_return_ok
        (return True) leave all the work to return_ok.

        If domain_return_ok returns true for the cookie domain, path_return_ok
        is called for the cookie path.  Otherwise, path_return_ok and return_ok
        are never called for that cookie domain.  If path_return_ok returns
        true, return_ok is called with the Cookie object itself for a full
        check.  Otherwise, return_ok is never called for that cookie path.

        Note that domain_return_ok is called for every *cookie* domain, not
        just for the *request* domain.  For example, the function might be
        called with both ".acme.com" and "www.acme.com" if the request domain
        is "www.acme.com".  The same goes for path_return_ok.

        For argument documentation, see the docstring for return_ok.

        """
        return True
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def domain_return_ok(self, domain, request):
        """Return false if cookies should not be returned, given cookie domain.

        This is here as an optimization, to remove the need for checking every
        cookie with a particular domain (which may involve reading many files).
        The default implementations of domain_return_ok and path_return_ok
        (return True) leave all the work to return_ok.

        If domain_return_ok returns true for the cookie domain, path_return_ok
        is called for the cookie path.  Otherwise, path_return_ok and return_ok
        are never called for that cookie domain.  If path_return_ok returns
        true, return_ok is called with the Cookie object itself for a full
        check.  Otherwise, return_ok is never called for that cookie path.

        Note that domain_return_ok is called for every *cookie* domain, not
        just for the *request* domain.  For example, the function might be
        called with both ".acme.com" and "www.acme.com" if the request domain
        is "www.acme.com".  The same goes for path_return_ok.

        For argument documentation, see the docstring for return_ok.

        """
        return True
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_firefox3_cookiejar_iteration(self):
        try:
            from mechanize import Firefox3CookieJar
        except ImportError:
            pass
        else:
            from mechanize import DefaultCookiePolicy
            filename = self.mktemp()
            hide_experimental_warnings()
            try:
                cj = Firefox3CookieJar(
                    filename, policy=DefaultCookiePolicy(rfc2965=True))
            finally:
                reset_experimental_warnings()
            cj.connect()
            self._interact(cj)
            summary = "\n".join([str(cookie) for cookie in cj])
            self.assertEquals(summary, """\
<Cookie foo2=bar for www.acme.com:80/>
<Cookie foo3=bar for www.acme.com/>
<Cookie foo1=bar for www.acme.com/>
<Cookie fooa=bar for www.foo.com/>
<Cookie foob=bar for .foo.com/>
<Cookie fooc=bar for .www.foo.com/>""")
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_netscape_misc(self):
        # Some additional Netscape cookies tests.
        from mechanize import CookieJar, Request

        c = CookieJar()
        headers = []
        req = Request("http://foo.bar.acme.com/foo")

        # Netscape allows a host part that contains dots
        headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        # and that the domain is the same as the host without adding a leading
        # dot to the domain.  Should not quote even if strange chars are used
        # in the cookie value.
        headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        req = Request("http://foo.bar.acme.com/foo")
        c.add_cookie_header(req)
        assert (req.get_header("Cookie").find("PART_NUMBER=3,4") != -1 and
                req.get_header("Cookie").find("Customer=WILE_E_COYOTE") != -1)
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def domain_return_ok(self, domain, request):
        """Return false if cookies should not be returned, given cookie domain.

        This is here as an optimization, to remove the need for checking every
        cookie with a particular domain (which may involve reading many files).
        The default implementations of domain_return_ok and path_return_ok
        (return True) leave all the work to return_ok.

        If domain_return_ok returns true for the cookie domain, path_return_ok
        is called for the cookie path.  Otherwise, path_return_ok and return_ok
        are never called for that cookie domain.  If path_return_ok returns
        true, return_ok is called with the Cookie object itself for a full
        check.  Otherwise, return_ok is never called for that cookie path.

        Note that domain_return_ok is called for every *cookie* domain, not
        just for the *request* domain.  For example, the function might be
        called with both ".acme.com" and "www.acme.com" if the request domain
        is "www.acme.com".  The same goes for path_return_ok.

        For argument documentation, see the docstring for return_ok.

        """
        return True
项目:BruteXSS    作者:rajeshmajumdar    | 项目源码 | 文件源码
def domain_return_ok(self, domain, request):
        """Return false if cookies should not be returned, given cookie domain.

        This is here as an optimization, to remove the need for checking every
        cookie with a particular domain (which may involve reading many files).
        The default implementations of domain_return_ok and path_return_ok
        (return True) leave all the work to return_ok.

        If domain_return_ok returns true for the cookie domain, path_return_ok
        is called for the cookie path.  Otherwise, path_return_ok and return_ok
        are never called for that cookie domain.  If path_return_ok returns
        true, return_ok is called with the Cookie object itself for a full
        check.  Otherwise, return_ok is never called for that cookie path.

        Note that domain_return_ok is called for every *cookie* domain, not
        just for the *request* domain.  For example, the function might be
        called with both ".acme.com" and "www.acme.com" if the request domain
        is "www.acme.com".  The same goes for path_return_ok.

        For argument documentation, see the docstring for return_ok.

        """
        return True
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def __str__(self):
        if self.port is None: p = ""
        else: p = ":"+self.port
        limit = self.domain + p + self.path
        if self.value is not None:
            namevalue = "%s=%s" % (self.name, self.value)
        else:
            namevalue = self.name
        return "<Cookie %s for %s>" % (namevalue, limit)
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def __repr__(self):
        args = []
        for name in ["version", "name", "value",
                     "port", "port_specified",
                     "domain", "domain_specified", "domain_initial_dot",
                     "path", "path_specified",
                     "secure", "expires", "discard", "comment", "comment_url",
                     ]:
            attr = getattr(self, name)
            args.append("%s=%s" % (name, repr(attr)))
        args.append("rest=%s" % repr(self._rest))
        args.append("rfc2109=%s" % repr(self.rfc2109))
        return "Cookie(%s)" % ", ".join(args)
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def set_ok(self, cookie, request):
        """Return true if (and only if) cookie should be accepted from server.

        Currently, pre-expired cookies never get this far -- the CookieJar
        class deletes such cookies itself.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.extract_cookies.__doc__

        """
        raise NotImplementedError()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def return_ok(self, cookie, request):
        """Return true if (and only if) cookie should be returned to server.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.add_cookie_header.__doc__

        """
        raise NotImplementedError()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def add_cookie_header(self, request):
        """Add correct Cookie: header to request (mechanize.Request object).

        The Cookie2 header is also added unless policy.hide_cookie2 is true.

        The request object (usually a mechanize.Request instance) must support
        the methods get_full_url, get_host, is_unverifiable, get_type,
        has_header, get_header, header_items and add_unredirected_header, as
        documented by urllib2.
        """
        debug("add_cookie_header")
        cookies = self.cookies_for_request(request)

        attrs = self._cookie_attrs(cookies)
        if attrs:
            if not request.has_header("Cookie"):
                request.add_unredirected_header("Cookie", "; ".join(attrs))

        # if necessary, advertise that we know RFC 2965
        if self._policy.rfc2965 and not self._policy.hide_cookie2:
            for cookie in cookies:
                if cookie.version != 1 and not request.has_header("Cookie2"):
                    request.add_unredirected_header("Cookie2", '$Version="1"')
                    break

        self.clear_expired_cookies()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object.

        See extract_cookies.__doc__ for the interface required of the
        response and request arguments.

        """
        self._policy._now = self._now = int(time.time())
        return [cookie for cookie in self._make_cookies(response, request)
                if cookie.expires is None or not cookie.expires <= self._now]
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def set_cookie_if_ok(self, cookie, request):
        """Set a cookie if policy says it's OK to do so.

        cookie: mechanize.Cookie instance
        request: see extract_cookies.__doc__ for the required interface

        """
        self._policy._now = self._now = int(time.time())

        if self._policy.set_ok(cookie, request):
            self.set_cookie(cookie)
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def set_cookie(self, cookie):
        """Set a cookie, without checking whether or not it should be set.

        cookie: mechanize.Cookie instance
        """
        c = self._cookies
        if not c.has_key(cookie.domain): c[cookie.domain] = {}
        c2 = c[cookie.domain]
        if not c2.has_key(cookie.path): c2[cookie.path] = {}
        c3 = c2[cookie.path]
        c3[cookie.name] = cookie
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def __str__(self):
        if self.port is None: p = ""
        else: p = ":"+self.port
        limit = self.domain + p + self.path
        if self.value is not None:
            namevalue = "%s=%s" % (self.name, self.value)
        else:
            namevalue = self.name
        return "<Cookie %s for %s>" % (namevalue, limit)
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def __repr__(self):
        args = []
        for name in ["version", "name", "value",
                     "port", "port_specified",
                     "domain", "domain_specified", "domain_initial_dot",
                     "path", "path_specified",
                     "secure", "expires", "discard", "comment", "comment_url",
                     ]:
            attr = getattr(self, name)
            args.append("%s=%s" % (name, repr(attr)))
        args.append("rest=%s" % repr(self._rest))
        args.append("rfc2109=%s" % repr(self.rfc2109))
        return "Cookie(%s)" % ", ".join(args)
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def set_ok(self, cookie, request):
        """Return true if (and only if) cookie should be accepted from server.

        Currently, pre-expired cookies never get this far -- the CookieJar
        class deletes such cookies itself.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.extract_cookies.__doc__

        """
        raise NotImplementedError()
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def return_ok(self, cookie, request):
        """Return true if (and only if) cookie should be returned to server.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.add_cookie_header.__doc__

        """
        raise NotImplementedError()
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def add_cookie_header(self, request):
        """Add correct Cookie: header to request (mechanize.Request object).

        The Cookie2 header is also added unless policy.hide_cookie2 is true.

        The request object (usually a mechanize.Request instance) must support
        the methods get_full_url, get_host, is_unverifiable, get_type,
        has_header, get_header, header_items and add_unredirected_header, as
        documented by urllib2.
        """
        debug("add_cookie_header")
        cookies = self.cookies_for_request(request)

        attrs = self._cookie_attrs(cookies)
        if attrs:
            if not request.has_header("Cookie"):
                request.add_unredirected_header("Cookie", "; ".join(attrs))

        # if necessary, advertise that we know RFC 2965
        if self._policy.rfc2965 and not self._policy.hide_cookie2:
            for cookie in cookies:
                if cookie.version != 1 and not request.has_header("Cookie2"):
                    request.add_unredirected_header("Cookie2", '$Version="1"')
                    break

        self.clear_expired_cookies()
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object.

        See extract_cookies.__doc__ for the interface required of the
        response and request arguments.

        """
        self._policy._now = self._now = int(time.time())
        return [cookie for cookie in self._make_cookies(response, request)
                if cookie.expires is None or not cookie.expires <= self._now]
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def set_cookie_if_ok(self, cookie, request):
        """Set a cookie if policy says it's OK to do so.

        cookie: mechanize.Cookie instance
        request: see extract_cookies.__doc__ for the required interface

        """
        self._policy._now = self._now = int(time.time())

        if self._policy.set_ok(cookie, request):
            self.set_cookie(cookie)
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def set_cookie(self, cookie):
        """Set a cookie, without checking whether or not it should be set.

        cookie: mechanize.Cookie instance
        """
        c = self._cookies
        if not c.has_key(cookie.domain): c[cookie.domain] = {}
        c2 = c[cookie.domain]
        if not c2.has_key(cookie.path): c2[cookie.path] = {}
        c3 = c2[cookie.path]
        c3[cookie.name] = cookie
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def __str__(self):
        if self.port is None: p = ""
        else: p = ":"+self.port
        limit = self.domain + p + self.path
        if self.value is not None:
            namevalue = "%s=%s" % (self.name, self.value)
        else:
            namevalue = self.name
        return "<Cookie %s for %s>" % (namevalue, limit)
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def __repr__(self):
        args = []
        for name in ["version", "name", "value",
                     "port", "port_specified",
                     "domain", "domain_specified", "domain_initial_dot",
                     "path", "path_specified",
                     "secure", "expires", "discard", "comment", "comment_url",
                     ]:
            attr = getattr(self, name)
            args.append("%s=%s" % (name, repr(attr)))
        args.append("rest=%s" % repr(self._rest))
        args.append("rfc2109=%s" % repr(self.rfc2109))
        return "Cookie(%s)" % ", ".join(args)
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def set_ok(self, cookie, request):
        """Return true if (and only if) cookie should be accepted from server.

        Currently, pre-expired cookies never get this far -- the CookieJar
        class deletes such cookies itself.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.extract_cookies.__doc__

        """
        raise NotImplementedError()
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def return_ok(self, cookie, request):
        """Return true if (and only if) cookie should be returned to server.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.add_cookie_header.__doc__

        """
        raise NotImplementedError()
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def add_cookie_header(self, request):
        """Add correct Cookie: header to request (mechanize.Request object).

        The Cookie2 header is also added unless policy.hide_cookie2 is true.

        The request object (usually a mechanize.Request instance) must support
        the methods get_full_url, get_host, is_unverifiable, get_type,
        has_header, get_header, header_items and add_unredirected_header, as
        documented by urllib2.
        """
        debug("add_cookie_header")
        cookies = self.cookies_for_request(request)

        attrs = self._cookie_attrs(cookies)
        if attrs:
            if not request.has_header("Cookie"):
                request.add_unredirected_header("Cookie", "; ".join(attrs))

        # if necessary, advertise that we know RFC 2965
        if self._policy.rfc2965 and not self._policy.hide_cookie2:
            for cookie in cookies:
                if cookie.version != 1 and not request.has_header("Cookie2"):
                    request.add_unredirected_header("Cookie2", '$Version="1"')
                    break

        self.clear_expired_cookies()
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object.

        See extract_cookies.__doc__ for the interface required of the
        response and request arguments.

        """
        self._policy._now = self._now = int(time.time())
        return [cookie for cookie in self._make_cookies(response, request)
                if cookie.expires is None or not cookie.expires <= self._now]
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def set_cookie_if_ok(self, cookie, request):
        """Set a cookie if policy says it's OK to do so.

        cookie: mechanize.Cookie instance
        request: see extract_cookies.__doc__ for the required interface

        """
        self._policy._now = self._now = int(time.time())

        if self._policy.set_ok(cookie, request):
            self.set_cookie(cookie)
项目:kodi-tk_del    作者:hubsif    | 项目源码 | 文件源码
def set_cookie(self, cookie):
        """Set a cookie, without checking whether or not it should be set.

        cookie: mechanize.Cookie instance
        """
        c = self._cookies
        if not c.has_key(cookie.domain): c[cookie.domain] = {}
        c2 = c[cookie.domain]
        if not c2.has_key(cookie.path): c2[cookie.path] = {}
        c3 = c2[cookie.path]
        c3[cookie.name] = cookie
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def interact_netscape(cookiejar, url, *set_cookie_hdrs):
    return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie")
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
    """Perform a single request / response cycle, returning Cookie: header."""
    req = Request(url)
    cookiejar.add_cookie_header(req)
    cookie_hdr = req.get_header("Cookie", "")
    headers = []
    for hdr in set_cookie_hdrs:
        headers.append("%s: %s" % (hdr_name, hdr))
    res = FakeResponse(headers, url)
    cookiejar.extract_cookies(res, req)
    return cookie_hdr
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_missing_name(self):
        from mechanize import MozillaCookieJar, lwp_cookie_str

        # missing = sign in Cookie: header is regarded by Mozilla as a missing
        # NAME.  WE regard it as a missing VALUE.
        filename = tempfile.mktemp()
        c = MozillaCookieJar(filename)
        interact_netscape(c, "http://www.acme.com/", 'eggs')
        interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
        cookie = c._cookies["www.acme.com"]["/"]['eggs']
        assert cookie.name == "eggs"
        assert cookie.value is None
        cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
        assert cookie.name == '"spam"'
        assert cookie.value is None
        assert lwp_cookie_str(cookie) == (
            r'"spam"; path="/foo/"; domain="www.acme.com"; '
            'path_spec; discard; version=0')
        old_str = repr(c)
        c.save(ignore_expires=True, ignore_discard=True)
        try:
            c = MozillaCookieJar(filename)
            c.revert(ignore_expires=True, ignore_discard=True)
        finally:
            os.unlink(c.filename)
        # cookies unchanged apart from lost info re. whether path was specified
        assert repr(c) == \
            re.sub("path_specified=%s" % True, "path_specified=%s" % False,
                   old_str)
        assert interact_netscape(c, "http://www.acme.com/foo/") == \
            '"spam"; eggs'
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_ns_parser_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from mechanize import CookieJar

        c = CookieJar()
        interact_netscape(c, "http://www.acme.com/", 'expires=eggs')
        interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')

        cookies = c._cookies["www.acme.com"]["/"]
        self.assert_('expires' in cookies)
        self.assert_('version' in cookies)
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_domain_block(self):
        from mechanize import CookieJar, DefaultCookiePolicy

        #import logging; logging.getLogger("mechanize").setLevel(logging.DEBUG)

        pol = DefaultCookiePolicy(rfc2965=True, blocked_domains=[".acme.com"])
        c = CookieJar(policy=pol)
        headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]

        req = Request("http://www.acme.com/")
        res = FakeResponse(headers, "http://www.acme.com/")
        c.extract_cookies(res, req)
        assert len(c) == 0

        pol.set_blocked_domains(["acme.com"])
        c.extract_cookies(res, req)
        assert len(c) == 1

        c.clear()
        req = Request("http://www.roadrunner.net/")
        res = FakeResponse(headers, "http://www.roadrunner.net/")
        c.extract_cookies(res, req)
        assert len(c) == 1
        req = Request("http://www.roadrunner.net/")
        c.add_cookie_header(req)
        assert (req.has_header("Cookie") and req.has_header("Cookie2"))

        c.clear()
        pol.set_blocked_domains([".acme.com"])
        c.extract_cookies(res, req)
        assert len(c) == 1

        # set a cookie with blocked domain...
        req = Request("http://www.acme.com/")
        res = FakeResponse(headers, "http://www.acme.com/")
        cookies = c.make_cookies(res, req)
        c.set_cookie(cookies[0])
        assert len(c) == 2
        # ... and check it doesn't get returned
        c.add_cookie_header(req)
        assert not req.has_header("Cookie")
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_missing_final_slash(self):
        # Missing slash from request URL's abs_path should be assumed present.
        from mechanize import CookieJar, Request, DefaultCookiePolicy
        url = "http://www.acme.com"
        c = CookieJar(DefaultCookiePolicy(rfc2965=True))
        interact_2965(c, url, "foo=bar; Version=1")
        req = Request(url)
        assert len(c) == 1
        c.add_cookie_header(req)
        assert req.has_header("Cookie")
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_Cookie_iterator(self):
        from mechanize import CookieJar, Cookie, DefaultCookiePolicy

        cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
        # add some random cookies
        interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
                      'Comment="does anybody read these?"; '
                      'CommentURL="http://foo.bar.net/comment.html"')
        interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; secure; Version=1")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; path=/; Version=1")
        interact_2965(cs, "http://www.sol.no",
                      r'bang=wallop; version=1; domain=".sol.no"; '
                      r'port="90,100, 80,8080"; '
                      r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')

        versions = [1, 1, 1, 0, 1]
        names = ["bang", "foo", "foo", "spam", "foo"]
        domains = [
            ".sol.no", "blah.spam.org", "www.acme.com", "www.acme.com",
            "www.acme.com"
        ]
        paths = ["/", "/", "/", "/blah", "/blah/"]

        # sequential iteration
        for i in range(4):
            i = 0
            for c in cs:
                # assert isinstance(c, Cookie)
                assert c.version == versions[i]
                assert c.name == names[i]
                assert c.domain == domains[i]
                assert c.path == paths[i]
                i = i + 1

        self.assertRaises(IndexError, lambda cs=cs: cs[5])
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_bad_cookie_header(self):
        def cookiejar_from_cookie_headers(headers):
            from mechanize import CookieJar, Request
            c = CookieJar()
            req = Request("http://www.example.com/")
            r = FakeResponse(headers, "http://www.example.com/")
            c.extract_cookies(r, req)
            return c

        # none of these bad headers should cause an exception to be raised
        for headers in [
            ["Set-Cookie: "],  # actually, nothing wrong with this
            ["Set-Cookie2: "],  # ditto
                # missing domain value
            ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
                # bad max-age
            ["Set-Cookie: b=foo; max-age=oops"],
                # bad version
            ["Set-Cookie: b=foo; version=spam"],
        ]:
            c = cookiejar_from_cookie_headers(headers)
            # these bad cookies shouldn't be set
            assert len(c) == 0

        # cookie with invalid expires is treated as session cookie
        headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
        c = cookiejar_from_cookie_headers(headers)
        cookie = c._cookies["www.example.com"]["/"]["c"]
        assert cookie.expires is None

        # cookie with unset path should have path=/
        headers = ["Set-Cookie: c=foo; path; expires=Foo Bar 12 33:22:11 2000"]
        c = cookiejar_from_cookie_headers(headers)
        assert ('www.example.com' in c._cookies and
                '/' in c._cookies['www.example.com'])
项目:mechanize    作者:python-mechanize    | 项目源码 | 文件源码
def test_firefox3_cookiejar_add_cookie_header(self):
        try:
            from mechanize import Firefox3CookieJar
        except ImportError:
            pass
        else:
            filename = self.mktemp()
            hide_experimental_warnings()
            try:
                cj = Firefox3CookieJar(filename)
            finally:
                reset_experimental_warnings()
            cj.connect()
            # Session cookies (true .discard) and persistent cookies (false
            # .discard) are stored differently.  Check they both get sent.
            year_plus_one = time.localtime(time.time())[0] + 1
            expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one, )
            interact_netscape(cj, "http://www.foo.com/", "fooa=bar")
            interact_netscape(cj, "http://www.foo.com/",
                              "foob=bar; %s" % expires)
            ca, cb = cj
            self.assert_(ca.discard)
            self.assertFalse(cb.discard)
            request = Request("http://www.foo.com/")
            cj.add_cookie_header(request)
            self.assertEquals(
                request.get_header("Cookie"), "fooa=bar; foob=bar")
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def __str__(self):
        if self.port is None: p = ""
        else: p = ":"+self.port
        limit = self.domain + p + self.path
        if self.value is not None:
            namevalue = "%s=%s" % (self.name, self.value)
        else:
            namevalue = self.name
        return "<Cookie %s for %s>" % (namevalue, limit)
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def __repr__(self):
        args = []
        for name in ["version", "name", "value",
                     "port", "port_specified",
                     "domain", "domain_specified", "domain_initial_dot",
                     "path", "path_specified",
                     "secure", "expires", "discard", "comment", "comment_url",
                     ]:
            attr = getattr(self, name)
            args.append("%s=%s" % (name, repr(attr)))
        args.append("rest=%s" % repr(self._rest))
        args.append("rfc2109=%s" % repr(self.rfc2109))
        return "Cookie(%s)" % ", ".join(args)
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def set_ok(self, cookie, request):
        """Return true if (and only if) cookie should be accepted from server.

        Currently, pre-expired cookies never get this far -- the CookieJar
        class deletes such cookies itself.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.extract_cookies.__doc__

        """
        raise NotImplementedError()
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def return_ok(self, cookie, request):
        """Return true if (and only if) cookie should be returned to server.

        cookie: mechanize.Cookie object
        request: object implementing the interface defined by
         CookieJar.add_cookie_header.__doc__

        """
        raise NotImplementedError()
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def add_cookie_header(self, request):
        """Add correct Cookie: header to request (mechanize.Request object).

        The Cookie2 header is also added unless policy.hide_cookie2 is true.

        The request object (usually a mechanize.Request instance) must support
        the methods get_full_url, get_host, is_unverifiable, get_type,
        has_header, get_header, header_items and add_unredirected_header, as
        documented by urllib2.
        """
        debug("add_cookie_header")
        cookies = self.cookies_for_request(request)

        attrs = self._cookie_attrs(cookies)
        if attrs:
            if not request.has_header("Cookie"):
                request.add_unredirected_header("Cookie", "; ".join(attrs))

        # if necessary, advertise that we know RFC 2965
        if self._policy.rfc2965 and not self._policy.hide_cookie2:
            for cookie in cookies:
                if cookie.version != 1 and not request.has_header("Cookie2"):
                    request.add_unredirected_header("Cookie2", '$Version="1"')
                    break

        self.clear_expired_cookies()
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object.

        See extract_cookies.__doc__ for the interface required of the
        response and request arguments.

        """
        self._policy._now = self._now = int(time.time())
        return [cookie for cookie in self._make_cookies(response, request)
                if cookie.expires is None or not cookie.expires <= self._now]
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def set_cookie_if_ok(self, cookie, request):
        """Set a cookie if policy says it's OK to do so.

        cookie: mechanize.Cookie instance
        request: see extract_cookies.__doc__ for the required interface

        """
        self._policy._now = self._now = int(time.time())

        if self._policy.set_ok(cookie, request):
            self.set_cookie(cookie)
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def set_cookie(self, cookie):
        """Set a cookie, without checking whether or not it should be set.

        cookie: mechanize.Cookie instance
        """
        c = self._cookies
        if not c.has_key(cookie.domain): c[cookie.domain] = {}
        c2 = c[cookie.domain]
        if not c2.has_key(cookie.path): c2[cookie.path] = {}
        c3 = c2[cookie.path]
        c3[cookie.name] = cookie
项目:BruteXSS    作者:rajeshmajumdar    | 项目源码 | 文件源码
def __str__(self):
        if self.port is None: p = ""
        else: p = ":"+self.port
        limit = self.domain + p + self.path
        if self.value is not None:
            namevalue = "%s=%s" % (self.name, self.value)
        else:
            namevalue = self.name
        return "<Cookie %s for %s>" % (namevalue, limit)
项目:BruteXSS    作者:rajeshmajumdar    | 项目源码 | 文件源码
def __repr__(self):
        args = []
        for name in ["version", "name", "value",
                     "port", "port_specified",
                     "domain", "domain_specified", "domain_initial_dot",
                     "path", "path_specified",
                     "secure", "expires", "discard", "comment", "comment_url",
                     ]:
            attr = getattr(self, name)
            args.append("%s=%s" % (name, repr(attr)))
        args.append("rest=%s" % repr(self._rest))
        args.append("rfc2109=%s" % repr(self.rfc2109))
        return "Cookie(%s)" % ", ".join(args)