Exemple #1
0
 def __init__(self,
              content_type=None,
              status=None,
              reason=None,
              charset=None):
     # _headers is a mapping of the lower-case name to the original case of
     # the header (required for working with legacy systems) and the header
     # value. Both the name of the header and its value are ASCII strings.
     self._headers = {}
     self._closable_objects = []
     # This parameter is set by the handler. It's necessary to preserve the
     # historical behavior of request_finished.
     self._handler_class = None
     self.cookies = SimpleCookie()
     self.closed = False
     if status is not None:
         self.status_code = status
     if reason is not None:
         self.reason_phrase = reason
     elif self.reason_phrase is None:
         self.reason_phrase = responses.get(self.status_code,
                                            'Unknown Status Code')
     self._charset = charset
     if content_type is None:
         content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
                                            self.charset)
     self['Content-Type'] = content_type
Exemple #2
0
def archive_error(request):
    """
    Replay content not found error page
    """

    # handle cors options for error page redirect from cors
    if request.method == 'OPTIONS':
        response = HttpResponse()
        set_options_headers(request, response)
        return response

    status_code = int(request.GET.get('status', '500'))
    response = render(
        request,
        'archive/archive-error.html', {
            'err_url': request.GET.get('url'),
            'timestamp': request.GET.get('timestamp'),
            'status': '{0} {1}'.format(status_code,
                                       responses.get(status_code)),
            'err_msg': request.GET.get('error'),
        },
        status=status_code)

    # even if not setting full headers (eg. if Origin is not set)
    # still set set Access-Control-Allow-Origin to content host to avoid Chrome CORB issues
    set_options_headers(request, response, always_set_allowed_origin=True)
    return response
Exemple #3
0
 def status_text(self):
     """
     Returns reason text corresponding to our HTTP response status code.
     Provided for convenience.
     """
     # TODO: Deprecate and use a template tag instead
     # TODO: Status code text for RFC 6585 status codes
     return responses.get(self.status_code, '')
 def status_text(self):
     """
     Returns reason text corresponding to our HTTP response status code.
     Provided for convenience.
     """
     # TODO: Deprecate and use a template tag instead
     # TODO: Status code text for RFC 6585 status codes
     return responses.get(self.status_code, '')
Exemple #5
0
def error_json_response(request, status_code, message=None, warning=None):
    data = {
        'timestamp': round(time() * 1000),
        'status': status_code,
        'error': responses.get(status_code, 'Unknown Status Code'),
        'path': request.path,
    }
    if message is not None:
        data['message'] = message
    if warning is not None:
        data['warning'] = warning
    response = Response(data, status=status_code)
    response.status_code = status_code
    return response
 def process_response(self, request, response):
     if 300 <= int(response.status_code) < 400:
         redirect_to = response.get('Location', None)
         if redirect_to:
             try:        # Django >= 1.6
                 reason_phrase = response.reason_phrase
             except AttributeError:
                 reason_phrase = responses.get(response.status_code,
                                               'UNKNOWN STATUS CODE')
             status_line = '%s %s' % (response.status_code, reason_phrase)
             cookies = response.cookies
             context = {'redirect_to': redirect_to, 'status_line': status_line}
             response = render_to_response('debug_toolbar/redirect.html', context)
             response.cookies = cookies
     return response
Exemple #7
0
 def __init__(self, content_type=None, status=None, reason=None, charset=None):
     # _headers is a mapping of the lower-case name to the original case of
     # the header (required for working with legacy systems) and the header
     # value. Both the name of the header and its value are ASCII strings.
     self._headers = {}
     self._closable_objects = []
     # This parameter is set by the handler. It's necessary to preserve the
     # historical behavior of request_finished.
     self._handler_class = None
     self.cookies = SimpleCookie()
     self.closed = False
     if status is not None:
         self.status_code = status
     if reason is not None:
         self.reason_phrase = reason
     elif self.reason_phrase is None:
         self.reason_phrase = responses.get(self.status_code, 'Unknown Status Code')
     self._charset = charset
     if content_type is None:
         content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
                                            self.charset)
     self['Content-Type'] = content_type
Exemple #8
0
 def reason_phrase(self):
     if self._reason_phrase is not None:
         return self._reason_phrase
     # Leave self._reason_phrase unset in order to use the default
     # reason phrase for status code.
     return responses.get(self.status_code, 'Unknown Status Code')
Exemple #9
0
    def __call__(self, environ, start_response):
        """
        Hijack the main loop from the original thread and listen on events on the Redis
        and the Websocket filedescriptors.
        """
        websocket = None
        subscriber = self.Subscriber(self._redis_connection)

        try:
            self.assure_protocol_requirements(environ)
            request = WSGIRequest(environ)
            if callable(settings.FLOW_WS_PROCESS_REQUEST):
                settings.FLOW_WS_PROCESS_REQUEST(request)
            else:
                self.process_request(request)
            channels, echo_message = self.process_subscriptions(request)
            if callable(settings.FLOW_WS_ALLOWED_CHANNELS):
                channels = list(settings.FLOW_WS_ALLOWED_CHANNELS(request, channels))
            websocket = self.upgrade_websocket(environ, start_response)
            logger.debug('Subscribed to channels: {0}'.format(', '.join(channels)))
            subscriber.set_pubsub_channels(request, channels)
            websocket_fd = websocket.get_file_descriptor()
            listening_fds = [websocket_fd]
            redis_fd = subscriber.get_file_descriptor()
            if redis_fd:
                listening_fds.append(redis_fd)
            subscriber.send_persited_messages(websocket)
            recvmsg = None
            while websocket and not websocket.closed:
                ready = self.select(listening_fds, [], [], 4.0)[0]
                if not ready:
                    # flush empty socket
                    websocket.flush()
                for fd in ready:
                    if fd == websocket_fd:
                        recvmsg = RedisMessage(websocket.receive())
                        if recvmsg:
                            subscriber.publish_message(recvmsg)
                    elif fd == redis_fd:
                        sendmsg = RedisMessage(subscriber.parse_response())
                        if sendmsg and (echo_message or sendmsg != recvmsg):
                            websocket.send(sendmsg)
                    else:
                        logger.error('Invalid file descriptor: {0}'.format(fd))
                if settings.FLOW_WS_HEARTBEAT:
                    websocket.send(settings.FLOW_WS_HEARTBEAT)
        except WebSocketError as excpt:
            logger.warning('WebSocketError: {}'.format(excpt), exc_info=sys.exc_info())
            response = http.HttpResponse(status=1001, content='Websocket Closed')
        except UpgradeRequiredError as excpt:
            logger.info('Websocket upgrade required')
            response = http.HttpResponseBadRequest(status=426, content=excpt)
        except HandshakeError as excpt:
            logger.warning('HandshakeError: {}'.format(excpt), exc_info=sys.exc_info())
            response = http.HttpResponseBadRequest(content=excpt)
        except PermissionDenied as excpt:
            logger.warning('PermissionDenied: {}'.format(excpt), exc_info=sys.exc_info())
            response = http.HttpResponseForbidden(content=excpt)
        except Exception as excpt:
            logger.error('Other Exception: {}'.format(excpt), exc_info=sys.exc_info())
            response = http.HttpResponseServerError(content=excpt)
        else:
            response = http.HttpResponse()
        finally:
            subscriber.release()
            if websocket:
                websocket.close(code=1001, message='Websocket Closed')
            else:
                logger.warning('Starting late response on websocket')
                status_text = responses.get(response.status_code, 'UNKNOWN STATUS CODE')
                status = '{0} {1}'.format(response.status_code, status_text)
                start_response(force_str(status), response._headers.values())
                logger.info('Finish non-websocket response with status code: {}'.format(response.status_code))
        return response
Exemple #10
0
 def reason_phrase(self):
     if self._reason_phrase is not None:
         return self._reason_phrase
     # Leave self._reason_phrase unset in order to use the default
     # reason phrase for status code.
     return responses.get(self.status_code, 'Unknown Status Code')
Exemple #11
0
    def __call__(self, environ, start_response):
        """
        Hijack the main loop from the original thread and listen on events on the Redis
        and the Websocket filedescriptors.
        """
        websocket = None
        subscriber = self.Subscriber(self._redis_connection)

        try:
            self.assure_protocol_requirements(environ)
            request = WSGIRequest(environ)
            if callable(settings.FLOW_WS_PROCESS_REQUEST):
                settings.FLOW_WS_PROCESS_REQUEST(request)
            else:
                self.process_request(request)
            channels, echo_message = self.process_subscriptions(request)
            if callable(settings.FLOW_WS_ALLOWED_CHANNELS):
                channels = list(
                    settings.FLOW_WS_ALLOWED_CHANNELS(request, channels))
            websocket = self.upgrade_websocket(environ, start_response)
            logger.debug('Subscribed to channels: {0}'.format(
                ', '.join(channels)))
            subscriber.set_pubsub_channels(request, channels)
            websocket_fd = websocket.get_file_descriptor()
            listening_fds = [websocket_fd]
            redis_fd = subscriber.get_file_descriptor()
            if redis_fd:
                listening_fds.append(redis_fd)
            subscriber.send_persited_messages(websocket)
            recvmsg = None
            while websocket and not websocket.closed:
                ready = self.select(listening_fds, [], [], 4.0)[0]
                if not ready:
                    # flush empty socket
                    websocket.flush()
                for fd in ready:
                    if fd == websocket_fd:
                        recvmsg = RedisMessage(websocket.receive())
                        if recvmsg:
                            subscriber.publish_message(recvmsg)
                    elif fd == redis_fd:
                        sendmsg = RedisMessage(subscriber.parse_response())
                        if sendmsg and (echo_message or sendmsg != recvmsg):
                            websocket.send(sendmsg)
                    else:
                        logger.error('Invalid file descriptor: {0}'.format(fd))
                if settings.FLOW_WS_HEARTBEAT:
                    websocket.send(settings.FLOW_WS_HEARTBEAT)
        except WebSocketError as excpt:
            logger.warning('WebSocketError: {}'.format(excpt),
                           exc_info=sys.exc_info())
            response = http.HttpResponse(status=1001,
                                         content='Websocket Closed')
        except UpgradeRequiredError as excpt:
            logger.info('Websocket upgrade required')
            response = http.HttpResponseBadRequest(status=426, content=excpt)
        except HandshakeError as excpt:
            logger.warning('HandshakeError: {}'.format(excpt),
                           exc_info=sys.exc_info())
            response = http.HttpResponseBadRequest(content=excpt)
        except PermissionDenied as excpt:
            logger.warning('PermissionDenied: {}'.format(excpt),
                           exc_info=sys.exc_info())
            response = http.HttpResponseForbidden(content=excpt)
        except Exception as excpt:
            logger.error('Other Exception: {}'.format(excpt),
                         exc_info=sys.exc_info())
            response = http.HttpResponseServerError(content=excpt)
        else:
            response = http.HttpResponse()
        finally:
            subscriber.release()
            if websocket:
                websocket.close(code=1001, message='Websocket Closed')
            else:
                logger.warning('Starting late response on websocket')
                status_text = responses.get(response.status_code,
                                            'UNKNOWN STATUS CODE')
                status = '{0} {1}'.format(response.status_code, status_text)
                start_response(force_str(status), response._headers.values())
                logger.info(
                    'Finish non-websocket response with status code: {}'.
                    format(response.status_code))
        return response
Exemple #12
0
 def status_text(self):
     """
     Returns reason text corresponding to our HTTP response status code.
     Provided for convenience.
     """
     return responses.get(self.status_code, '')
 def status_text(self):
     """
     Returns reason text corresponding to our HTTP response status code.
     Provided for convenience.
     """
     return responses.get(self.status_code, '')