Exemple #1
0
 def _wrap(response):
     cookie = SimpleCookie()
     cookie.load(response.headers['Set-Cookie'])
     for key, value in cookie.items():
         if key == ngw_env.pyramid.options['session.cookie.name']:
             return value.value
     return None
Exemple #2
0
 def fromRawString(raw):
     try:
         sc = SimpleCookie(raw)
         for key, cookie in sc.items():
             try:
                 return Cookie(key, cookie['domain'], cookie['path'], raw,
                               cookie['expires'], True)
             except:
                 return None
     except CookieError as e:
         print(e)
         return None
Exemple #3
0
class Response(object):
    """
    Describes an HTTP response. Currently very simple since the actual body
    of the request is handled separately.
    """
    def __init__(self):
        """
        Create a new Response defaulting to HTML content and "200 OK" status
        """
        self.status = "200 OK"
        self.headers = HeaderDict({"content-type": "text/html; charset=UTF-8"})
        self.cookies = SimpleCookie()

    def set_content_type(self, type_):
        """
        Sets the Content-Type header
        """
        self.headers["content-type"] = type_

    def get_content_type(self):
        return self.headers.get("content-type", None)

    def send_redirect(self, url):
        """
        Send an HTTP redirect response to (target `url`)
        """
        if "\n" in url or "\r" in url:
            raise webob.exc.HTTPInternalServerError(
                "Invalid redirect URL encountered.")
        raise webob.exc.HTTPFound(location=url,
                                  headers=self.wsgi_headeritems())

    def wsgi_headeritems(self):
        """
        Return headers in format appropriate for WSGI `start_response`
        """
        result = self.headers.headeritems()
        # Add cookie to header
        for name, crumb in self.cookies.items():
            header, value = str(crumb).split(': ', 1)
            result.append((header, value))
        return result

    def wsgi_status(self):
        """
        Return status line in format appropriate for WSGI `start_response`
        """
        if isinstance(self.status, int):
            exception = webob.exc.status_map.get(self.status)
            return "%d %s" % (exception.code, exception.title)
        else:
            return self.status
Exemple #4
0
class Response(object):
    """
    Describes an HTTP response. Currently very simple since the actual body
    of the request is handled separately.
    """

    def __init__(self):
        """
        Create a new Response defaulting to HTML content and "200 OK" status
        """
        self.status = "200 OK"
        self.headers = HeaderDict({"content-type": "text/html"})
        self.cookies = SimpleCookie()

    def set_content_type(self, type_):
        """
        Sets the Content-Type header
        """
        self.headers["content-type"] = type_

    def get_content_type(self):
        return self.headers.get("content-type", None)

    def send_redirect(self, url):
        """
        Send an HTTP redirect response to (target `url`)
        """
        if "\n" in url or "\r" in url:
            raise webob.exc.HTTPInternalServerError("Invalid redirect URL encountered.")
        raise webob.exc.HTTPFound(location=url)

    def wsgi_headeritems(self):
        """
        Return headers in format appropriate for WSGI `start_response`
        """
        result = self.headers.headeritems()
        # Add cookie to header
        for name, crumb in self.cookies.items():
            header, value = str(crumb).split(': ', 1)
            result.append((header, value))
        return result

    def wsgi_status(self):
        """
        Return status line in format appropriate for WSGI `start_response`
        """
        if isinstance(self.status, int):
            exception = webob.exc.status_map.get(self.status)
            return "%d %s" % (exception.code, exception.title)
        else:
            return self.status
Exemple #5
0
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
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