Exemple #1
0
 async def render_response(self) -> TextResponse:
     env = Environment(
         loader=PackageLoader("crax", "templates/"),
         enable_async=True,
         autoescape=True,
     )
     template = env.get_template(self.template)
     self.format_traceback(self.ex)
     content = await template.render_async(**self.context)
     response = TextResponse(self.request,
                             content,
                             status_code=self.status_code)
     response.status_code = self.status_code
     return response
Exemple #2
0
 async def __call__(self, scope, receive, send):
     if self.request.method == "POST":
         self.context = {"data": self.request.post["data"]}
         response = JSONResponse(self.request, self.context)
     else:
         response = TextResponse(self.request, "Text content")
     await response(scope, receive, send)
Exemple #3
0
    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        if self.request.method == "GET":
            self.request.status_code = 200
            response = await self.get()

        elif self.request.method == "POST":
            self.request.status_code = 201
            response = await self.post()

        elif self.request.method == "PUT":
            self.request.status_code = 204
            response = await self.put()

        elif self.request.method == "PATCH":
            self.request.status_code = 204
            response = await self.patch()

        elif self.request.method == "DELETE":
            self.request.status_code = 204
            response = await self.delete()
        else:
            response = TextResponse(self.request,
                                    b"",
                                    status_code=self.status_code)

        if response is not None:
            await response(scope, receive, send)
Exemple #4
0
async def guest_view_coroutine(request, scope, receive, send):
    env = Environment(
        loader=PackageLoader("tests.test_app_common", "templates/"), autoescape=True
    )
    template = env.get_template("index.html")
    content = template.render()
    response = TextResponse(request, content)
    await response(scope, receive, send)
Exemple #5
0
 async def post(self):
     self.context = {"data": self.request.post["data"]}
     env = Environment(
         loader=PackageLoader("tests.test_app_common", "templates/"),
         autoescape=True,
     )
     template = env.get_template("index.html")
     content = template.render(self.context)
     response = TextResponse(self.request, content)
     return response
Exemple #6
0
 def dispatch(self) -> typing.Callable:
     if not self.request.path.endswith("/"):
         self.static_dirs += ["swagger/static/"]
         detect_static = [
             x for x in self.request.path.split("/")
             if x in self.static_dirs or re.match(r"(\w+\.)(png|ico|css|js|jpeg|jpg)", x)
         ]
     else:
         detect_static = None
     if detect_static:
         try:
             crax_path = __import__(FileResponse.__module__)
             path = f"{crax_path.__path__[0]}{self.request.path}"
             os.stat(path)
             response = FileResponse(path)
         except FileNotFoundError:
             try:
                 os.stat(self.request.path)
                 response = FileResponse(self.request.path)
             except FileNotFoundError:
                 try:
                     os.stat(self.request.path[1:])
                     response = FileResponse(self.request.path[1:])
                 except FileNotFoundError:
                     try:
                         path = self.base_url + self.request.path
                         os.stat(path)
                         response = FileResponse(path)
                     except FileNotFoundError as e:
                         response = TextResponse(self.request, b"File not found", status_code=404)
     else:
         resolver = self.resolve_path()
         error = self.check_allowed(resolver)
         if not error:
             response = resolver
         else:
             if self.request.scheme in ["http", "http.request"]:
                 if self.debug is True:
                     response = DefaultError(
                         self.request,
                         error["error_handler"](error["error_message"]),
                         status_code=error["status_code"],
                     )
                 else:
                     response = get_error_handler(
                         error["error_handler"](error["error_message"])
                     )
             else:
                 raise error["error_handler"](error["error_message"])
     return response
Exemple #7
0
 async def __call__(self, scope, receive, send):
     if self.request.method == "POST":
         if isinstance(self.request.post, str):
             data = json.loads(self.request.post)
         else:
             data = self.request.post
         self.context = {"data": data["data"], "files": self.request.files}
         env = Environment(
             loader=PackageLoader("tests.test_app_common", "templates/"),
             autoescape=True,
         )
         template = env.get_template("index.html")
         content = template.render(self.context)
         response = TextResponse(self.request, content)
         await response(scope, receive, send)
Exemple #8
0
 async def render_response(self) -> TextResponse:
     if self.template:
         try:
             template = self.get_template()
             if self.request:
                 self.kwargs["user"] = self.request.user
             content = await template.render_async(**self.context)
             response = TextResponse(self.request,
                                     content,
                                     status_code=self.status_code)
         except TemplateNotFound as ex:
             self.status_code = 404
             content = await self.create_error_content(ex, 404)
             response = TextResponse(self.request, content)
     else:
         self.status_code = 500
         content = await self.create_error_content(
             CraxNoTemplateGiven(self.request.path), 500)
         response = TextResponse(self.request, content)
     response.status_code = self.status_code
     return response
Exemple #9
0
def get_error_handler(error: typing.Any) -> typing.Callable:
    error_handlers = get_settings_variable("ERROR_HANDLERS")
    if hasattr(error, 'status_code'):
        status_code = error.status_code
    else:
        status_code = 500
    handler = None
    if error_handlers is not None:
        if isinstance(error_handlers, dict) and error_handlers:
            try:
                if hasattr(error, "status_code"):
                    handler = error_handlers[f"{status_code}_handler"]
                else:
                    handler = error_handlers["500_handler"]
            except KeyError:  # pragma: no cover
                pass
    else:
        if hasattr(error, 'message'):
            message = error.message
        else:
            message = 'Internal server error'
        handler = TextResponse(None, message, status_code=status_code)
    return handler
Exemple #10
0
 async def __call__(self, scope, receive, send):
     response = TextResponse(self.request, b"Testing bytes")
     await response(scope, receive, send)
Exemple #11
0
 async def __call__(self, scope, receive, send):
     response = TextResponse(self.request, None)
     await response(scope, receive, send)
Exemple #12
0
 async def __call__(self, scope, receive, send):
     response = TextResponse(self.request, "Testing Custom View")
     await response(scope, receive, send)
Exemple #13
0
 async def __call__(self, scope, receive, send):
     response = TextResponse(self.request, "Testing Not Found")
     response.status_code = 404
     await response(scope, receive, send)
Exemple #14
0
    async def process_headers(self) -> typing.Any:
        response = await super(CorsHeadersMiddleware, self).process_headers()
        cors_options = get_settings_variable("CORS_OPTIONS", default={})
        preflight = True
        error = None
        status_code = 200
        if self.request.method == "OPTIONS":
            if not isinstance(cors_options, dict):
                error = RuntimeError("Cors options should be a dict")
                status_code = 500
                response = TextResponse(
                    self.request, str(error), status_code=status_code
                )
                return response

        origin = cors_options.get("origins", "*")
        method = cors_options.get("methods", "*")
        header = cors_options.get("headers", "*")
        expose_headers = cors_options.get("expose_headers", None)
        max_age = cors_options.get("max_age", "600")

        request_origin = self.request.headers.get("origin")
        request_method = self.request.headers.get("access-control-request-method")
        request_headers = self.request.headers.get("access-control-request-headers")

        if request_method is None:
            request_method = self.request.scope["method"]

        if self.request.method == "OPTIONS":
            if request_headers:
                request_headers = set(request_headers.split(","))
            else:
                request_headers = {"content-type"}
            request_method = {request_method}
            request_origin = {request_origin}
            if header != "*" and "cors_cookie" in cors_options:
                if "*" in header:
                    pass  # pragma: no cover
                else:
                    header = [x for x in header]
                    header.append(cors_options["cors_cookie"].lower())

            cors_headers = self.check_allowed(header, request_headers)
            if cors_headers is None:
                error = RuntimeError(
                    f"Cross Origin Request with headers: "
                    f'"{list(request_headers)[0]}" not allowed on this server'
                )
                status_code = 400
            cors_methods = self.check_allowed(method, request_method)
            if cors_methods is None:
                error = RuntimeError(
                    f"Cross Origin Request with method: "
                    f'"{list(request_method)[0]}" not allowed on this server'
                )
                status_code = 400

            cors_origins = self.check_allowed(origin, request_origin)
            if cors_origins is None:
                error = RuntimeError(
                    f"Cross Origin Request from: "
                    f'"{list(request_origin)[0]}" not allowed on this server'
                )
                status_code = 400

        elif (
            "cors_cookie" in cors_options
            and cors_options["cors_cookie"].lower() in self.request.headers
        ):
            preflight = False
            if not isinstance(origin, str):
                cors_origins = ", ".join(origin)
            else:
                cors_origins = origin

            if not isinstance(method, str):
                cors_methods = ", ".join(method)
            else:
                cors_methods = method
            if not isinstance(header, str):
                cors_headers = ", ".join(header)
            else:
                cors_headers = header
        else:
            return response

        if error is None:
            cors_headers = [
                (b"Access-Control-Allow-Origin", cors_origins.encode("latin-1")),
                (b"Access-Control-Allow-Methods", cors_methods.encode("latin-1")),
                (b"Access-Control-Allow-Headers", cors_headers.encode("latin-1")),
                (b"Access-Control-Max-Age", max_age.encode("latin-1")),
                (b"Vary", b"Origin"),
            ]

            if expose_headers is not None and preflight is True:
                if isinstance(expose_headers, str):
                    expose_headers = [x.strip() for x in expose_headers.split(",")]
                assert type(expose_headers) == list
                cors_headers.append(
                    (b"Access-Control-Expose-Headers", ", ".join(expose_headers).encode("latin-1"))
                )

            if preflight is False:
                if self.request.content_type is not None:
                    cors_headers.append(
                        (b"Content-Type", self.request.content_type.encode("latin-1"))
                    )
            self.headers.append(cors_headers)
            response.headers.extend(*self.headers)
        else:
            response = TextResponse(self.request, str(error), status_code=status_code)

        return response