def invoke(self, request: Request) -> Response:
        origin = request.headers['Origin']
        if self.should_allow(origin):
            response = Response(200, self.cors_headers, "")
        else:
            response = Response(400, self.cors_headers, "")

        if 'Vary' not in response.headers and response.headers[ALLOW_ORIGIN_HEADER] != '*':
            response.headers['Vary'] = 'Origin'

        return response
示例#2
0
    def test_givenATemplatedResponse_whenApplyingFilter_thenTheTemplateIsProcessedByJinja2(
            self):
        a_templated_response = Response(
            200, {}, RenderedView("test.html", {"foo": "bar"}))
        self.deserializerMock.is_deserializable_type.return_value = False
        self.viewTemplateRepositoryMock.get_template.return_value = A_TEMPLATE

        self.templateFilter.doFilter(A_REQUEST, a_templated_response,
                                     self.filterChainMock)

        self.assertEqual("bar", a_templated_response.body)
示例#3
0
    def invoke(self, request: Request) -> Response:
        try:
            method = types.MethodType(self.route_registration.routeFunction, self.get_resource_instance())
            parameters = self.parameter_selector_chain.get_parameters(request, method)
            function_return = method(*parameters)
        except MissingRouteInvocationArgument:
            raise IncorrectResourceParametersException()

        if isinstance(function_return, Response):
            return function_return
        return Response(200, {}, function_return)
示例#4
0
    def test_givenATemplatedResponse_whenApplyingFilter_thenContentTypeIsSetToTextHtml(
            self):
        a_templated_response = Response(
            200, {}, RenderedView("test.html", {"foo": "bar"}))
        self.viewTemplateRepositoryMock.get_template.return_value = A_TEMPLATE

        self.templateFilter.doFilter(A_REQUEST, a_templated_response,
                                     self.filterChainMock)

        self.assertEqual("text/html",
                         a_templated_response.headers['Content-Type'])
示例#5
0
    def handle_partial_content_request(
            self,
            request: Request,
            filepath: str,
            *,
            max_block_size: int = 2000000,
            content_type="application/octet-stream") -> Response:
        if request.headers['Range']:
            total_filesize = os.path.getsize(filepath)
            start, end = self._parse_range_string(request.headers['Range'],
                                                  max_block_size,
                                                  total_filesize)
            return Response(
                206, {
                    "Content-Type": content_type,
                    "Accept-Ranges": "bytes",
                    "Content-Range": f"bytes {start}-{end-1}/{total_filesize}"
                }, self._read_partial_file(filepath, start, end))

        return Response(200, {"Content-Type": content_type},
                        self._read_whole_file(filepath))
示例#6
0
    def test_givenADto_whenApplyingFilter_thenDtoIsSerializedToDictionaryBeforeRenderingTheTemplate(
            self):
        A_DTO = object()
        a_templated_response = Response(200, {},
                                        RenderedView("test.html", A_DTO))
        self.serializerMock.serialize.return_value = {"foo": "bar"}
        self.viewTemplateRepositoryMock.get_template.return_value = A_TEMPLATE

        self.templateFilter.doFilter(A_REQUEST, a_templated_response,
                                     self.filterChainMock)

        self.assertEqual("bar", a_templated_response.body)
示例#7
0
    def test_givenMatchingExceptionMapper_whenHandlingException_thenReturnTheCreatedHttpResponse(
            self):
        created_response = Response(200, {"foo": "bar"}, "body")
        self.exceptionMapperMock.handles.return_value = True
        self.exceptionMapperMock.create_response.return_value = created_response
        self.filterChainMock.doFilter.side_effect = AnException()

        returned_response = Response.empty()
        self.filter.doFilter(None, returned_response, self.filterChainMock)

        self.assertEqual(created_response.headers, returned_response.headers)
        self.assertEqual(created_response.body, returned_response.body)
        self.assertEqual(created_response.status, returned_response.status)
示例#8
0
    def post(self, request: Request) -> Response:
        filename = os.path.join(self.temp_dir, str(uuid.uuid4())) + ".pdf"
        new_filename = os.path.join(self.temp_dir, str(uuid.uuid4())) + ".pdf"

        with open(filename, 'wb') as f:
            f.write(request.body)

        subprocess.call(
            ("""pdfnup --nup 2x2 """ + filename +
             """ --papersize {8.5in,11in} -o """ + new_filename).split(" "))

        with open(new_filename, 'rb') as f:
            body = f.read()
        return Response(200, {}, body)
示例#9
0
    def post_file(self, request: Request) -> Response:
        filename = self.temporary_file_factory.generate_temporary_pdf_filepath(
        )

        dpi = 400
        if "HTTP_DPI" in request.headers.keys():
            dpi = int(request.headers["HTTP_DPI"])

        with open(filename, 'wb') as f:
            f.write(request.body)

        new_filename = self.conversion_service.convert(filename, dpi)

        with open(new_filename, 'rb') as f:
            body = f.read()
        return Response(200, {}, body)
示例#10
0
    def post_file(self, request: Request) -> Response:
        filename = os.path.join(self.temp_dir, str(uuid.uuid4())) + ".pdf"
        new_filename = os.path.join(self.temp_dir, str(uuid.uuid4())) + ".pdf"

        dpi = 100
        if "HTTP_DPI" in request.headers.keys():
            dpi = int(request.headers["HTTP_DPI"])

        with open(filename, 'wb') as f:
            f.write(request.body)

        subprocess.call(
            f"""convert -density {dpi} -negate {filename} {new_filename} """.
            split(" ")[:-1])

        with open(new_filename, 'rb') as f:
            body = f.read()
        return Response(200, {}, body)
 def serve_file(self) -> Response:
     with open(self.filepath, 'rb') as f:
         return Response(200, {}, f.read())
示例#12
0
 def preflight(self):
     headers = Headers()
     headers['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, DELETE"
     headers['Access-Control-Allow-Headers'] = '*'
     return Response(200, headers, "")
 def create_response(self, exception: Exception) -> Response:
     return Response(404, {}, {"message": "Resource Not Found"})
class ResourceClass(object):
    has_been_called = False

    the_response = Response(402, {}, "a response")

    @GET
    def a_method(self):
        ResourceClass.has_been_called = True
        return "hello"

    @GET
    @Path("/request")
    def a_method_which_requires_a_request(self, request: Request) -> Response:
        assert isinstance(request, Request)
        return self.the_response

    @POST
    @Path("/dictionary")
    def a_method_which_requires_a_dictionary(self, body: dict) -> Response:
        assert isinstance(body, dict)
        assert body == BODY
        return self.the_response

    @POST
    @Path("/dto")
    def a_method_which_requires_a_dto(self, body: A_Dto) -> Response:
        assert isinstance(body, A_Dto)
        assert body.name == DTO_BODY['name']
        return self.the_response

    @POST
    @Path("/dto-no-param")
    def a_method_which_requires_a_dto_without_a_constructor(
            self, body: ADtoWithoutAnExplicitConstructor) -> Response:
        assert isinstance(body, ADtoWithoutAnExplicitConstructor)
        assert body.name == DTO_BODY['name']
        assert body.a_dummy_function(
        ) == False  # assert function does not get overwritten
        return self.the_response

    @GET
    @Path("/return-dto")
    def returns_a_dto(self) -> A_Dto:
        return A_Dto("a_name")

    @GET
    @Path("/path-param/{name}")
    def with_path_param(self, name: PathParam[str]) -> str:
        assert isinstance(name, str)
        return name

    @GET
    @Path("/numeric-param/{number}")
    def with_numeric_path_param(self, number: PathParam[int]) -> int:
        assert isinstance(number, int)
        return number

    @GET
    @Path("/query-param")
    def with_query_param(self, name: QueryParam[str]) -> str:
        assert isinstance(name, str)
        return name

    @GET
    @Path("/overloaded")
    def overloaded_param(self, name: QueryParam[str]) -> int:
        return 5

    OVERLOADED_RETURN = 6

    @GET
    @Path("/overloaded")
    def overloaded_without_name_parameter(self, query: QueryParam[str]) -> int:
        return self.OVERLOADED_RETURN

    @GET
    @Path("/nullable-query")
    def nullable_query(self, query: OptionalQueryParam[str]) -> Optional[str]:
        return query

    @GET
    @Path("/error")
    def raises_error(self) -> str:
        raise AnException

    @GET
    @Path("/headers")
    def get_with_headers(self, headers: Headers) -> list:
        return headers.items()
 def create_response(self, exception: Exception) -> Response:
     return Response(400, {}, {"message": "Incorrect parameters"})
示例#16
0
 def read_raw_request(self, request: Request) -> Response:
     return Response(200, {}, "body")
示例#17
0
 def create_response(self, exception: Exception) -> Response:
     return Response(418, {}, "Error! I am a teapot!")
示例#18
0
 def create_response(self, exception: Exception) -> Response:
     return Response(405, {}, {"message": "Method not allowed"})
示例#19
0
 def get_stream(self) -> Response:
     # A Response object can also be manually created to provide further control over transport parameters.
     return Response(202, Headers(), StreamingResponseBody(self.generate_bytes()))
示例#20
0
 def create_response(self, exception: Exception) -> Response:
     return Response(
         400, {},
         "An error occurred while converting this file. Make sure that you are uploading a valid PDF file and try again."
     )
示例#21
0
 def create_response(self, exception: Exception) -> Response:
     return Response(
         400, {},
         "The operation took too long to complete. Try lowering the DPI or using smaller PDF files."
     )
 def create_response(self, exception: Exception) -> Response:
     return Response(400, {}, {"message": "Missing CORS rule."})
示例#23
0
 def read_request(self, request: Request) -> Response:
     print(request)
     return Response(402, {}, str(request))
示例#24
0
 def get_album_artwork(self, album_id: PathParam[str]) -> Response:
     artwork = self.artwork_repository.get_artwork(UUID(album_id))
     return Response(200, {'Content-Type': artwork.mime_type}, artwork.data)
示例#25
0
 def build(self):
     return Response(self._status, self._headers, self._body)