Exemple #1
0
 def add(self, cookiestr):
     try:
         cookies = self._cookies_from_attrs_set(
             split_header_words([cookiestr]), None)
     except BaseException:
         cookies = []
     for cookie in cookies:
         self.set_cookie(cookie)
Exemple #2
0
 def do_meta(self, attrs):
     equiv = get("http-equiv", attrs)
     content = get("content", attrs)
     if equiv != "content-type": return
     attrs = cookielib.split_header_words([content])[0]
     encoding = get("charset", attrs)
     if encoding == "ASCII": encoding = "ISO-8859-1"
     if encoding: self.encoding = encoding
 def do_meta(self, attrs):
     equiv = get("http-equiv", attrs)
     content = get("content", attrs)
     if equiv != "content-type":
         return
     attrs = cookielib.split_header_words([content])[0]
     encoding = get("charset", attrs)
     if encoding == "ASCII":
         encoding = "ISO-8859-1"
     if encoding:
         self.encoding = encoding
Exemple #4
0
    def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object."""
        # get cookie-attributes for RFC 2965 and Netscape protocols
        headers = response.info()
        rfc2965_hdrs = headers.getheaders("Set-Cookie2")
        ns_hdrs = headers.getheaders("Set-Cookie")

        rfc2965 = self._policy.rfc2965
        netscape = self._policy.netscape

        if netscape:
            for cookie in self._cookies_from_attrs_set(cookielib.parse_ns_headers(ns_hdrs), request):
                self._process_rfc2109_cookies([cookie])
                yield cookie

        if rfc2965:
            for cookie in self._cookies_from_attrs_set(cookielib.split_header_words(rfc2965_hdrs), request):
                yield cookie
Exemple #5
0
    def __call__(self, environ, start_response):
        """WSGI interface

        In:
          - ``environ`` -- dictionary of the received elements
          - ``start_response`` -- callback to send the headers to the browser

        Return:
          - the content to send back to the browser
        """
        # Clean-up the cookies because Bespin can generate invalid cookies for WebOb
        cookies = environ.get('HTTP_COOKIE')
        if cookies:
            cookies = cookielib.split_header_words([cookies])
            cookies = [(k, v) for (k, v) in cookies[0] if not k.startswith('viewData_Nagare_')]
            environ['HTTP_COOKIE'] = cookielib.join_header_words([cookies])

        return super(WSGIApp, self).__call__(environ, start_response)
Exemple #6
0
    def make_cookies(self, response, request):
        """Return sequence of Cookie objects extracted from response object."""
        # get cookie-attributes for RFC 2965 and Netscape protocols
        headers = response.info()
        rfc2965_hdrs = headers.getheaders("Set-Cookie2")
        ns_hdrs = headers.getheaders("Set-Cookie")

        rfc2965 = self._policy.rfc2965
        netscape = self._policy.netscape

        if netscape:
            for cookie in self._cookies_from_attrs_set(
                    cookielib.parse_ns_headers(ns_hdrs), request):
                self._process_rfc2109_cookies([cookie])
                yield cookie

        if rfc2965:
            for cookie in self._cookies_from_attrs_set(
                    cookielib.split_header_words(rfc2965_hdrs), request):
                yield cookie
Exemple #7
0
def from_headers (strheader):
    """Parse cookie data from a string in HTTP header (RFC 2616) format.

    @return: list of cookies
    @raises: ValueError for incomplete or invalid data
    """
    res = []
    fp = StringIO(strheader)
    headers = httplib.HTTPMessage(fp, seekable=True)
    if "Host" not in headers:
        raise ValueError("Required header 'Host:' missing")
    host = headers["Host"]
    path= headers.get("Path", "/")
    for header in headers.getallmatchingheaders("Set-Cookie"):
        headervalue = header.split(':', 1)[1]
        for pairs in cookielib.split_header_words([headervalue]):
            for name, value in pairs:
                cookie = requests.cookies.create_cookie(name, value,
                    domain=host, path=path)
                res.append(cookie)
    return res
Exemple #8
0
def from_headers(strheader):
    """Parse cookie data from a string in HTTP header (RFC 2616) format.

    @return: list of cookies
    @raises: ValueError for incomplete or invalid data
    """
    res = []
    fp = StringIO(strheader)
    headers = httplib.HTTPMessage(fp, seekable=True)
    if "Host" not in headers:
        raise ValueError("Required header 'Host:' missing")
    host = headers["Host"]
    path = headers.get("Path", "/")
    for header in headers.getallmatchingheaders("Set-Cookie"):
        headervalue = header.split(':', 1)[1]
        for pairs in cookielib.split_header_words([headervalue]):
            for name, value in pairs:
                cookie = requests.cookies.create_cookie(name,
                                                        value,
                                                        domain=host,
                                                        path=path)
                res.append(cookie)
    return res
    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        magic = f.readline()
        if not re.search(self.magic_re, magic):
            msg = '%r does not look like a Set-Cookie3 (LWP) format file' % filename
            raise LoadError(msg)
        now = time.time()
        header = 'Set-Cookie3:'
        boolean_attrs = ('port_spec', 'path_spec', 'domain_dot', 'secure',
                         'discard')
        value_attrs = ('version', 'port', 'path', 'domain', 'expires',
                       'comment', 'commenturl')
        try:
            while 1:
                line = f.readline()
                if line == '':
                    break
                if not line.startswith(header):
                    continue
                line = line[len(header):].strip()
                for data in split_header_words([line]):
                    name, value = data[0]
                    standard = {}
                    rest = {}
                    for k in boolean_attrs:
                        standard[k] = False

                    for k, v in data[1:]:
                        if k is not None:
                            lc = k.lower()
                        else:
                            lc = None
                        if lc in value_attrs or lc in boolean_attrs:
                            k = lc
                        if k in boolean_attrs:
                            if v is None:
                                v = True
                            standard[k] = v
                        elif k in value_attrs:
                            standard[k] = v
                        else:
                            rest[k] = v

                    h = standard.get
                    expires = h('expires')
                    discard = h('discard')
                    if expires is not None:
                        expires = iso2time(expires)
                    if expires is None:
                        discard = True
                    domain = h('domain')
                    domain_specified = domain.startswith('.')
                    c = Cookie(h('version'), name, value, h('port'),
                               h('port_spec'), domain, domain_specified,
                               h('domain_dot'), h('path'), h('path_spec'),
                               h('secure'), expires, discard, h('comment'),
                               h('commenturl'), rest)
                    if not ignore_discard and c.discard:
                        continue
                    if not ignore_expires and c.is_expired(now):
                        continue
                    self.set_cookie(c)

        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError('invalid Set-Cookie3 format file %r: %r' %
                            (filename, line))

        return
    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        magic = f.readline()
        if not re.search(self.magic_re, magic):
            msg = '%r does not look like a Set-Cookie3 (LWP) format file' % filename
            raise LoadError(msg)
        now = time.time()
        header = 'Set-Cookie3:'
        boolean_attrs = ('port_spec', 'path_spec', 'domain_dot', 'secure', 'discard')
        value_attrs = ('version', 'port', 'path', 'domain', 'expires', 'comment', 'commenturl')
        try:
            while 1:
                line = f.readline()
                if line == '':
                    break
                if not line.startswith(header):
                    continue
                line = line[len(header):].strip()
                for data in split_header_words([line]):
                    name, value = data[0]
                    standard = {}
                    rest = {}
                    for k in boolean_attrs:
                        standard[k] = False

                    for k, v in data[1:]:
                        if k is not None:
                            lc = k.lower()
                        else:
                            lc = None
                        if lc in value_attrs or lc in boolean_attrs:
                            k = lc
                        if k in boolean_attrs:
                            if v is None:
                                v = True
                            standard[k] = v
                        elif k in value_attrs:
                            standard[k] = v
                        else:
                            rest[k] = v

                    h = standard.get
                    expires = h('expires')
                    discard = h('discard')
                    if expires is not None:
                        expires = iso2time(expires)
                    if expires is None:
                        discard = True
                    domain = h('domain')
                    domain_specified = domain.startswith('.')
                    c = Cookie(h('version'), name, value, h('port'), h('port_spec'), domain, domain_specified, h('domain_dot'), h('path'), h('path_spec'), h('secure'), expires, discard, h('comment'), h('commenturl'), rest)
                    if not ignore_discard and c.discard:
                        continue
                    if not ignore_expires and c.is_expired(now):
                        continue
                    self.set_cookie(c)

        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError('invalid Set-Cookie3 format file %r: %r' % (filename, line))

        return
Exemple #11
-2
    def _really_load(self, f, filename, ignore_discard, ignore_expires):
        magic = f.readline()
        if not re.search(self.magic_re, magic):
            msg = ("%r does not look like a Set-Cookie3 (LWP) format "
                   "file" % filename)
            raise LoadError(msg)

        now = time.time()

        header = "Set-Cookie3:"
        boolean_attrs = ("port_spec", "path_spec", "domain_dot",
                         "secure", "discard")
        value_attrs = ("version",
                       "port", "path", "domain",
                       "expires",
                       "comment", "commenturl")

        try:
            while 1:
                line = f.readline()
                if line == "": break
                if not line.startswith(header):
                    continue
                line = line[len(header):].strip()

                for data in split_header_words([line]):
                    name, value = data[0]
                    standard = {}
                    rest = {}
                    for k in boolean_attrs:
                        standard[k] = False
                    for k, v in data[1:]:
                        if k is not None:
                            lc = k.lower()
                        else:
                            lc = None
                        # don't lose case distinction for unknown fields
                        if (lc in value_attrs) or (lc in boolean_attrs):
                            k = lc
                        if k in boolean_attrs:
                            if v is None: v = True
                            standard[k] = v
                        elif k in value_attrs:
                            standard[k] = v
                        else:
                            rest[k] = v

                    h = standard.get
                    expires = h("expires")
                    discard = h("discard")
                    if expires is not None:
                        expires = iso2time(expires)
                    if expires is None:
                        discard = True
                    domain = h("domain")
                    domain_specified = domain.startswith(".")
                    c = Cookie(h("version"), name, value,
                               h("port"), h("port_spec"),
                               domain, domain_specified, h("domain_dot"),
                               h("path"), h("path_spec"),
                               h("secure"),
                               expires,
                               discard,
                               h("comment"),
                               h("commenturl"),
                               rest)
                    if not ignore_discard and c.discard:
                        continue
                    if not ignore_expires and c.is_expired(now):
                        continue
                    self.set_cookie(c)

        except IOError:
            raise
        except Exception:
            _warn_unhandled_exception()
            raise LoadError("invalid Set-Cookie3 format file %r: %r" %
                            (filename, line))