예제 #1
0
        def wrapper(self, event, *args, **kwargs):
            try:
                if not hasattr(self, "request"):
                    (self.request, self.response), args = args[:2], args[2:]
                    self.request.args = args
                    self.request.kwargs = kwargs
                    self.cookie = self.request.cookie
                    if hasattr(self.request, "session"):
                        self.session = self.request.session

                if hasattr(self, "_auth"):
                    self._auth()

                if not getattr(f, "event", False):
                    result = f(self, *args, **kwargs)
                else:
                    result = f(self, event, *args, **kwargs)
                if (isinstance(result, httperror)
                        or isinstance(result, Response)
                        or isinstance(result, six.string_types)):
                    return result
                elif result is None:
                    self.response.status = 204
                    return ""
                else:
                    try:
                        self.response.headers[
                            "Content-Type"] = "application/json; charset=utf-8"
                        return json.dumps(result)
                    except (JSONDecodeError, TypeError) as e:
                        return httperror(
                            self.request,
                            self.response,
                            code=500,
                            description=
                            "JSON decode failed for object of type '%s'" %
                            type(result))
            except HTTPException as e:
                LOG.exception(e)
                return httperror(self.request,
                                 self.response,
                                 code=e.code,
                                 description=e.description)
            except Exception as e:
                LOG.exception(e)
                return httperror(self.request,
                                 self.response,
                                 code=500,
                                 description=e.message)
            finally:
                if hasattr(self, "request"):
                    del self.request
                    del self.response
                    del self.cookie
                if hasattr(self, "session"):
                    del self.session
예제 #2
0
    def _on_request(self, event, request, response):
        if self._path is not None and not request.path.startswith(self._path):
            return

        self._protocol_version = 13
        headers = request.headers
        sec_key = headers.get("Sec-WebSocket-Key", "").encode("utf-8")
        subprotocols = headers.elements("Sec-WebSocket-Protocol")

        connection_tokens = [
            s.strip() for s in headers.get("Connection", "").lower().split(",")
        ]

        try:
            if ("Host" not in headers
                    or headers.get("Upgrade", "").lower() != "websocket"
                    or "upgrade" not in connection_tokens or sec_key is None
                    or len(base64.b64decode(sec_key)) != 16):
                return httperror(request, response, code=400)
            if headers.get("Sec-WebSocket-Version", "") != "13":
                response.headers["Sec-WebSocket-Version"] = "13"
                return httperror(request, response, code=400)

            # Generate accept header information
            msg = sec_key + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
            hasher = hashlib.sha1()
            hasher.update(msg)
            accept = base64.b64encode(hasher.digest())

            # Successful completion
            response.status = 101
            response.close = False
            try:
                del response.headers["Content-Type"]
            except KeyError:
                pass
            response.headers["Upgrade"] = "WebSocket"
            response.headers["Connection"] = "Upgrade"
            response.headers["Sec-WebSocket-Accept"] = accept.decode("ASCII")
            if subprotocols:
                response.headers[
                    "Sec-WebSocket-Protocol"] = self.select_subprotocol(
                        subprotocols)
            codec = WebSocketCodec(request.sock, channel=self._wschannel)
            self._codecs[request.sock] = codec
            codec.register(self)
            return response
        finally:
            event.stop()
예제 #3
0
def serve_tenjin(engine, request, response, path, context, 
                 type=None, disposition=None, name=None, globexts=None):
    if not engine and not os.path.isabs(path):
        raise ValueError("'%s' is not an absolute path." % path)

    if type is None:
        # Set content-type based on filename extension
        type, _ = mimetypes.guess_type(path, False)
        if type is None:
            type = "text/plain"
    response.headers['Content-Type'] = type

    if disposition is not None:
        if name is None:
            name = os.path.basename(path)
        cd = '%s; filename="%s"' % (disposition, name)
        response.headers["Content-Disposition"] = cd

    if globexts:
        globs = tenjin.helpers.__dict__.copy()
        globs.update(globexts)
    else:
        globs = tenjin.helpers.__dict__
    #tenjin.helpers.

    try:
        response.body = engine.render(path, context, globals = globs)
    except Exception as error:
        etype, evalue, etraceback = sys.exc_info()
        error = (etype, evalue, traceback.format_tb(etraceback))
        return httperror(request, response, 500, error=error)        
    return response
예제 #4
0
    def _on_request(self, event, request, response):
        if self._path is not None and not request.path.startswith(self._path):
            return

        self._protocol_version = 13
        headers = request.headers
        sec_key = headers.get("Sec-WebSocket-Key", "").encode("utf-8")

        connection_tokens = [s.strip() for s in
                             headers.get("Connection", "").lower().split(",")]

        try:
            if ("Host" not in headers
                or headers.get("Upgrade", "").lower() != "websocket"
                or "upgrade" not in connection_tokens
                or sec_key is None
                    or len(base64.b64decode(sec_key)) != 16):
                return httperror(request, response, code=400)
            if headers.get("Sec-WebSocket-Version", "") != "13":
                response.headers["Sec-WebSocket-Version"] = "13"
                return httperror(request, response, code=400)

            # Generate accept header information
            msg = sec_key + b("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
            hasher = hashlib.sha1()
            hasher.update(msg)
            accept = base64.b64encode(hasher.digest())

            # Successful completion
            response.status = 101
            response.close = False
            try:
                del response.headers["Content-Type"]
            except KeyError:
                pass
            response.headers["Upgrade"] = "WebSocket"
            response.headers["Connection"] = "Upgrade"
            response.headers["Sec-WebSocket-Accept"] = accept.decode()
            codec = WebSocketCodec(request.sock, channel=self._wschannel)
            self._codecs[request.sock] = codec
            codec.register(self)
            return response
        finally:
            event.stop()
예제 #5
0
    def _on_request(self, event, request, response):
        if "authorization" in request.headers:
            ah = _httpauth.parseAuthorization(request.headers["authorization"])
            if ah is None:
                event.stop()
                return httperror(request, response, 400)

            username, password = ah["username"], ah["password"]

            if check_auth(username, password):
                request.login = username
                return

        response.headers["WWW-Authenticate"] = _httpauth.basicAuth(self.realm)

        event.stop()
        return unauthorized(request, response)
예제 #6
0
파일: main.py 프로젝트: prologic/todoapp
    def serialize_response_body(self, event, response):
        template = response.body
        if not isinstance(template, JinjaTemplate):
            return

        try:
            request = response.request

            try:
                tmpl = self.env.get_template("{0}.html".format(template.name))
            except TemplateNotFound:
                raise NotFound()

            ctx = self.defaults.copy()
            ctx.update({"request": request, "response": response, "uri": request.uri})

            ctx.update(template.context)

            response.body = tmpl.render(**ctx)
        except:
            event.stop()
            evalue, etype, etraceback = sys.exc_info()
            error = (evalue, etype, format_tb(etraceback))
            self.fire(httperror(request, response, 500, error=error))