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


Python SimpleCookie.load方法代码示例

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


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

示例1: CookieHandler

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
class CookieHandler(object):

    def __init__(self, *args, **kw):
        # Somewhere to store cookies between consecutive requests
        self.cookies = SimpleCookie()
        super(CookieHandler, self).__init__(*args, **kw)

    def httpCookie(self, path):
        """Return self.cookies as an HTTP_COOKIE environment value."""
        l = [m.OutputString().split(';')[0] for m in self.cookies.values()
             if path.startswith(m['path'])]
        return '; '.join(l)

    def loadCookies(self, envstring):
        self.cookies.load(envstring)

    def saveCookies(self, response):
        """Save cookies from the response."""
        # Urgh - need to play with the response's privates to extract
        # cookies that have been set
        # TODO: extend the IHTTPRequest interface to allow access to all
        # cookies
        # TODO: handle cookie expirations
        for k, v in response._cookies.items():
            k = k.encode('utf8') if bytes is str else k
            val = v['value']
            val = val.encode('utf8') if bytes is str else val
            self.cookies[k] = val
            if 'path' in v:
                self.cookies[k]['path'] = v['path']
开发者ID:zopefoundation,项目名称:zope.app.testing,代码行数:32,代码来源:functional.py

示例2: _prepare_response

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
    def _prepare_response(self, res_info, url):

        res = requests.Response()
        res.url = res_info.get('url', url)
        res.status_code = res_info.get('status_code', 200)
        res.reason_phrase = res_info.get('reason_phrase', REASON_PHRASES.get(res.status_code, 'UNKNOWN STATUS CODE'))

        if 'reason' in res_info:
            res.reason = res_info['reason']

        if 'headers' in res_info:
            res.headers.update(res_info['headers'])

            if 'Set-Cookie' in res_info['headers'] and 'cookies' not in res_info:
                cookies = SimpleCookie()
                for entry in res_info['headers']['Set-Cookie'].split(','):
                    cookies.load(str(entry))
                res.cookies.update(cookies)

        if 'cookies' in res_info:
            res.cookies.update(res_info['cookies'])

        res.raw = StreamContent(res_info.get('content', ''))

        return res
开发者ID:Wirecloud,项目名称:wirecloud,代码行数:27,代码来源:testcases.py

示例3: _assert_cookies_expired

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
    def _assert_cookies_expired(self, http_headers):
        cookies_string = ";".join([c[1] for c in http_headers if c[0] == "Set-Cookie"])
        all_cookies = SimpleCookie()
        all_cookies.load(cookies_string)

        now = datetime.datetime.utcnow()  #
        for c in [self.provider.cookie_name, self.provider.session_cookie_name]:
            dt = datetime.datetime.strptime(all_cookies[c]["expires"], "%a, %d-%b-%Y %H:%M:%S GMT")
            assert dt < now  # make sure the cookies have expired to be cleared
开发者ID:htobenothing,项目名称:pyoidc,代码行数:11,代码来源:test_oic_provider.py

示例4: extract_macaroons

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
def extract_macaroons(headers_or_request):
    ''' Returns an array of any macaroons found in the given slice of cookies.
    If the argument implements a get_header method, that will be used
    instead of the get method to retrieve headers.
    @param headers_or_request: dict of headers or a
    urllib.request.Request-like object.
    @return: A list of list of mpy macaroons
    '''
    def get_header(key, default=None):
        try:
            return headers_or_request.get_header(key, default)
        except AttributeError:
            return headers_or_request.get(key, default)

    mss = []

    def add_macaroon(data):
        try:
            data = utils.b64decode(data)
            data_as_objs = json.loads(data.decode('utf-8'))
        except ValueError:
            return
        ms = [utils.macaroon_from_dict(x) for x in data_as_objs]
        mss.append(ms)

    cookie_header = get_header('Cookie')
    if cookie_header is not None:
        cs = SimpleCookie()
        # The cookie might be a unicode object, so convert it
        # to ASCII. This may cause an exception under Python 2.
        # TODO is that a problem?
        cs.load(str(cookie_header))
        for c in cs:
            if c.startswith('macaroon-'):
                add_macaroon(cs[c].value)
    # Python doesn't make it easy to have multiple values for a
    # key, so split the header instead, which is necessary
    # for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2)
    macaroon_header = get_header('Macaroons')
    if macaroon_header is not None:
        for h in macaroon_header.split(','):
            add_macaroon(h)
    return mss
开发者ID:go-macaroon-bakery,项目名称:py-macaroon-bakery,代码行数:45,代码来源:_client.py

示例5: _prepare_response

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
    def _prepare_response(self, res_info, url):

        res = requests.Response()
        res.url = res_info.get("url", url)
        res.status_code = res_info.get("status_code", 200)
        res.reason_phrase = res_info.get("reason_phrase", REASON_PHRASES.get(res.status_code, "UNKNOWN STATUS CODE"))

        if "reason" in res_info:
            res.reason = res_info["reason"]

        if "headers" in res_info:
            res.headers.update(res_info["headers"])

            if "Set-Cookie" in res_info["headers"]:
                cookies = SimpleCookie()
                for entry in res_info["headers"]["Set-Cookie"].split(","):
                    cookies.load(str(entry))
                res.cookies.update(cookies)

        res.raw = StreamContent(res_info.get("content", ""))

        return res
开发者ID:GreenIDer-Donati,项目名称:wirecloud,代码行数:24,代码来源:testcases.py

示例6: _generate_proxy

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
def _generate_proxy(current_path, value):
    where = value.split(':', 1)[1]
    cookie_name, routes = where.split(':', 1)
    routes = dict([ route.strip().split('=', 1) for route in routes.split(',') if route.strip() ])

    # cookie_name = 'weblabsessionid'
    # routes = {
    #    'route1' : 'http://localhost:10000/weblab/json/',
    #    'route2' : 'http://localhost:10001/weblab/json/',
    #    'route3' : 'http://localhost:10002/weblab/json/',
    # }

    current_cookie_value = request.cookies.get(cookie_name, '')

    chosen_url = None
    for route in routes:
        if current_cookie_value.endswith(route):
            chosen_url = routes[route]
            break

    if chosen_url is None:
        chosen_url = random.choice(list(routes.values()))

    headers = dict(request.headers)
    headers['X-Forwarded-For'] = request.remote_addr
    headers['X-Forwarded-Host'] = request.host
    headers.pop('Host', None)
    headers.pop('host', None)

    kwargs = dict(headers = headers, cookies = dict(request.cookies), allow_redirects=False)

    if request.method == 'GET':
        method = requests.get
    elif request.method == 'POST':
        kwargs['data'] = request.data

        if request.files:
            kwargs['files'] = {}
            for f, f_contents in six.iteritems(request.files):
                kwargs['files'][f] = [f_contents.filename, f_contents.stream, f_contents.content_type, f_contents.headers]

        if request.form:
            headers.pop('Content-Type', None)
            kwargs['data'] = request.form

        method = requests.post
    else:
        raise Exception("Method not supported")

    MAX_RETRIES = 5
    retry = 0
    full_url = chosen_url + current_path
    if request.args:
        full_url += '?' + '&'.join([ '%s=%s' % (key, requests.utils.quote(value, '')) for key, value in request.args.items() ])

    while True:
        try:
            req = method(full_url, **kwargs)
            break
        except requests.ConnectionError:
            if request.method != 'GET':
                raise
            retry += 1
            if retry >= MAX_RETRIES:
                raise
            time.sleep(0.5)

    cookies = list(req.cookies)
   
    headers = dict(req.headers)
    headers.pop('set-cookie', None)
    response_kwargs = {
        'headers' : headers,
        'status' : req.status_code,
    }
    if 'content-type' in req.headers:
        response_kwargs['content_type'] = req.headers['content-type']
    
    response = Response(req.content, **response_kwargs)
    
    existing_cookies = SimpleCookie()
    for header in response.headers:
        if header[0].lower() == 'set-cookie':
            try:
                if six.PY2:
                    cookie_header = header[1].encode('utf8')
                else:
                    cookie_header = header[1]
                existing_cookies.load(cookie_header)
            except Exception as e:
                print("Error processing cookie header: {}".format(cookie_header))
                import traceback
                traceback.print_exc()

    for c in req.cookies:
        if c.name not in existing_cookies.keys():
            response.set_cookie(c.name, c.value, path=c.path, expires=c.expires, secure=c.secure)

    return response
开发者ID:labsland,项目名称:weblabdeusto,代码行数:101,代码来源:proxy_server.py

示例7: BaseHeaders

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
class BaseHeaders(CaseInsensitiveMapping):
    """Represent the headers in an HTTP Request or Response message.

    `How to send non-English unicode string using HTTP header?
    <http://stackoverflow.com/q/5423223/>`_ and
    `What character encoding should I use for a HTTP header?
    <http://stackoverflow.com/q/4400678/>`_
    have good notes on why we do everything as pure bytes here.
    """

    def __init__(self, d):
        """Takes headers as a dict, list, or bytestring.
        """
        if isinstance(d, bytes):
            from pando.exceptions import MalformedHeader

            def genheaders():
                for line in d.splitlines():
                    if b':' not in line:
                        # no colon separator in header
                        raise MalformedHeader(line)
                    k, v = line.split(b':', 1)
                    if k != k.strip():
                        # disallowed leading or trailing whitspace
                        # (per http://tools.ietf.org/html/rfc7230#section-3.2.4)
                        raise MalformedHeader(line)
                    yield k, v.strip()

            headers = genheaders()
        else:
            headers = d
        CaseInsensitiveMapping.__init__(self, headers)

        # Cookie
        # ======

        self.cookie = SimpleCookie()
        cookie = self.get(b'Cookie', b'')
        if PY3 and isinstance(cookie, bytes):
            cookie = cookie.decode('ascii', 'replace')
        try:
            self.cookie.load(cookie)
        except CookieError:
            pass  # XXX really?

    def __setitem__(self, name, value):
        """Checks for CRLF in ``value``, then calls the superclass method:

        .. automethod:: pando.http.mapping.CaseInsensitiveMapping.__setitem__
        """
        _check_for_CRLF(value)
        super(BaseHeaders, self).__setitem__(name, value)

    def add(self, name, value):
        """Checks for CRLF in ``value``, then calls the superclass method:

        .. automethod:: pando.http.mapping.CaseInsensitiveMapping.add
        """
        _check_for_CRLF(value)
        super(BaseHeaders, self).add(name, value)

    @property
    def raw(self):
        """Return the headers as a bytestring, formatted for an HTTP message.
        """
        out = []
        for header, values in sorted(self.items()):
            for value in values:
                out.append(header + b': ' + value)
        return b'\r\n'.join(out)
开发者ID:AspenWeb,项目名称:pando.py,代码行数:72,代码来源:baseheaders.py

示例8: Request

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]

#.........这里部分代码省略.........
        self.hooks.run('before_finalize')
        response.finalize()

    def process_query_string(self):
        """Parse the query string into Python structures. (Core)"""
        try:
            p = httputil.parse_query_string(
                self.query_string, encoding=self.query_string_encoding)
        except UnicodeDecodeError:
            raise cherrypy.HTTPError(
                404, 'The given query string could not be processed. Query '
                'strings for this resource must be encoded with %r.' %
                self.query_string_encoding)

        # Python 2 only: keyword arguments must be byte strings (type 'str').
        if six.PY2:
            for key, value in p.items():
                if isinstance(key, six.text_type):
                    del p[key]
                    p[key.encode(self.query_string_encoding)] = value
        self.params.update(p)

    def process_headers(self):
        """Parse HTTP header data into Python structures. (Core)"""
        # Process the headers into self.headers
        headers = self.headers
        for name, value in self.header_list:
            # Call title() now (and use dict.__method__(headers))
            # so title doesn't have to be called twice.
            name = name.title()
            value = value.strip()

            headers[name] = httputil.decode_TEXT_maybe(value)

            # Some clients, notably Konquoror, supply multiple
            # cookies on different lines with the same key. To
            # handle this case, store all cookies in self.cookie.
            if name == 'Cookie':
                try:
                    self.cookie.load(value)
                except CookieError as exc:
                    raise cherrypy.HTTPError(400, str(exc))

        if not dict.__contains__(headers, 'Host'):
            # All Internet-based HTTP/1.1 servers MUST respond with a 400
            # (Bad Request) status code to any HTTP/1.1 request message
            # which lacks a Host header field.
            if self.protocol >= (1, 1):
                msg = "HTTP/1.1 requires a 'Host' request header."
                raise cherrypy.HTTPError(400, msg)
        host = dict.get(headers, 'Host')
        if not host:
            host = self.local.name or self.local.ip
        self.base = '%s://%s' % (self.scheme, host)

    def get_resource(self, path):
        """Call a dispatcher (which sets self.handler and .config). (Core)"""
        # First, see if there is a custom dispatch at this URI. Custom
        # dispatchers can only be specified in app.config, not in _cp_config
        # (since custom dispatchers may not even have an app.root).
        dispatch = self.app.find_config(
            path, 'request.dispatch', self.dispatch)

        # dispatch() should set self.handler and self.config
        dispatch(path)

    def handle_error(self):
        """Handle the last unanticipated exception. (Core)"""
        try:
            self.hooks.run('before_error_response')
            if self.error_response:
                self.error_response()
            self.hooks.run('after_error_response')
            cherrypy.serving.response.finalize()
        except cherrypy.HTTPRedirect:
            inst = sys.exc_info()[1]
            inst.set_response()
            cherrypy.serving.response.finalize()

    # ------------------------- Properties ------------------------- #

    def _get_body_params(self):
        warnings.warn(
            'body_params is deprecated in CherryPy 3.2, will be removed in '
            'CherryPy 3.3.',
            DeprecationWarning
        )
        return self.body.params
    body_params = property(_get_body_params,
                           doc="""
    If the request Content-Type is 'application/x-www-form-urlencoded' or
    multipart, this will be a dict of the params pulled from the entity
    body; that is, it will be the portion of request.params that come
    from the message body (sometimes called "POST params", although they
    can be sent with various HTTP method verbs). This value is set between
    the 'before_request_body' and 'before_handler' hooks (assuming that
    process_request_body is True).

    Deprecated in 3.2, will be removed for 3.3 in favor of
    :attr:`request.body.params<cherrypy._cprequest.RequestBody.params>`.""")
开发者ID:Southpaw-TACTIC,项目名称:TACTIC,代码行数:104,代码来源:_cprequest.py

示例9: call_wsgi_app

# 需要导入模块: from six.moves.http_cookies import SimpleCookie [as 别名]
# 或者: from six.moves.http_cookies.SimpleCookie import load [as 别名]
def call_wsgi_app(wsgi_app, request, path_info):
    """
    Call the ``wsgi_app`` with ``request`` and return its response.
    
    :param wsgi_app: The WSGI application to be run.
    :type wsgi_app: callable
    :param request: The Django request.
    :type request: :class:`django_wsgi.handler.DjangoWSGIRequest`
    :param path_info: The ``PATH_INFO`` to be used by the WSGI application.
    :type path: :class:`basestring`
    :raises django_wsgi.exc.ApplicationCallError: If ``path_info`` is not the
        last portion of the ``PATH_INFO`` in ``request``.
    :return: The response from the WSGI application, turned into a Django
        response.
    :rtype: :class:`django.http.HttpResponse`
    
    """
    webob_request = request.webob
    new_request = webob_request.copy()
    
    # Moving the portion of the path consumed by the current view, from the
    # PATH_INTO to the SCRIPT_NAME:
    if not request.path_info.endswith(path_info):
        raise ApplicationCallError("Path %s is not the last portion of the "
                                   "PATH_INFO in the original request (%s)"
                                   % (path_info, request.path_info))
    consumed_path = request.path_info[:-len(path_info)]
    new_request.path_info = path_info
    new_request.script_name = webob_request.script_name + consumed_path
    
    # If the user has been authenticated in Django, log him in the WSGI app:
    if request.user.is_authenticated():
        new_request.remote_user = request.user.username
    
    # Cleaning the routing_args, if any. The application should have its own
    # arguments, without relying on any arguments from a parent application:
    if "wsgiorg.routing_args" in request.environ:
        del new_request.environ['wsgiorg.routing_args']
    # And the same for the WebOb ad-hoc attributes:
    if "webob.adhoc_attrs" in request.environ:
        del new_request.environ['webob.adhoc_attrs']
    
    # Calling the WSGI application and getting its response:
    (status_line, headers, body) = new_request.call_application(wsgi_app)
    
    status_code_raw = status_line.split(" ", 1)[0]
    status_code = int(status_code_raw)
    
    # Turning its response into a Django response:
    cookies = SimpleCookie()
    django_response = HttpResponse(body, status=status_code)
    for (header, value) in headers:
        if header.upper() == "SET-COOKIE":
            if PY2 and isinstance(value, text_type):
                # It can't be Unicode:
                value = value.encode("us-ascii")
            cookies.load(value)
        else:
            django_response[header] = value
    
    # Setting the cookies from Django:
    for (cookie_name, cookie) in cookies.items():
        cookie_attributes = {
            'key': cookie_name,
            'value': cookie.value,
            'expires': cookie['expires'],
            'path': cookie['path'],
            'domain': cookie['domain'],
            }
        if cookie['max-age']:
            # Starting in Django 1.3 it performs arithmetic operations
            # with 'Max-Age'
            cookie_attributes['max_age'] = int(cookie['max-age'])

        django_response.set_cookie(**cookie_attributes)
    return django_response
开发者ID:2degrees,项目名称:django-wsgi,代码行数:78,代码来源:embedded_wsgi.py


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