コード例 #1
0
ファイル: test_app.py プロジェクト: jamesls/chalice
def test_http_response_to_dict(body, headers, status_code):
    r = Response(body=body, headers=headers, status_code=status_code)
    serialized = r.to_dict()
    assert 'headers' in serialized
    assert 'statusCode' in serialized
    assert 'body' in serialized
    assert isinstance(serialized['body'], six.string_types)
コード例 #2
0
ファイル: test_app.py プロジェクト: abdullah353/chalice
def test_http_response_to_dict(body, headers, status_code):
    r = Response(body=body, headers=headers, status_code=status_code)
    serialized = r.to_dict()
    assert 'headers' in serialized
    assert 'statusCode' in serialized
    assert 'body' in serialized
    assert isinstance(serialized['body'], six.string_types)
コード例 #3
0
ファイル: test_app.py プロジェクト: jamesls/chalice
def test_handles_binary_responses(body, content_type):
    r = Response(body=body, headers={'Content-Type': content_type})
    serialized = r.to_dict(BINARY_TYPES)
    # A binary response should always result in the
    # response being base64 encoded.
    assert serialized['isBase64Encoded']
    assert isinstance(serialized['body'], six.string_types)
    assert isinstance(base64.b64decode(serialized['body']), bytes)
コード例 #4
0
ファイル: test_app.py プロジェクト: abdullah353/chalice
def test_handles_binary_responses(body, content_type):
    r = Response(body=body, headers={'Content-Type': content_type})
    serialized = r.to_dict(BINARY_TYPES)
    # A binary response should always result in the
    # response being base64 encoded.
    assert serialized['isBase64Encoded']
    assert isinstance(serialized['body'], six.string_types)
    assert isinstance(base64.b64decode(serialized['body']), bytes)
コード例 #5
0
    def execute_request(self, request: Request) -> Response:
        """
        Parse the request process it with strawberry and return a response
        Args:
            request: The chalice request this contains the headers and body

        Returns:
            A chalice response
        """
        if self.graphiql:
            if (self.has_html_been_asked_for(request.headers)
                    and request.method == "GET"):
                graphiql_page: str = self.render_graphiql()
                return Response(
                    body=graphiql_page,
                    headers={"content-type": "text/html"},
                    status_code=200,
                )

        if not request.method == "POST":
            return self.invalid_rest_verb_response()

        try:
            request_data = request.json_body
        except BadRequestError:
            return self.invalid_query_response()

        if request_data is None:
            return self.invalid_query_response()
        try:
            query = request_data["query"]
            variables = request_data.get("variables")
            operation_name = request_data.get("operationName")

        except (KeyError, TypeError):
            return self.invalid_query_response()

        result: ExecutionResult = self._schema.execute_sync(
            query,
            variable_values=variables,
            context_value=request,
            operation_name=operation_name,
            root_value=None,
        )

        http_result: GraphQLHTTPResponse = process_result(result)

        return Response(body=http_result)
コード例 #6
0
def get_swagger_ui_bundle():
    """Get Swagger UI Bundle JS Endpoint

    Returns:
        str: Return JavaScript for Swagger UI from static folder
    """
    ui_js_file = "swagger-ui-bundle.js"
    logger.info(f"Endpoint: Get CSS : {ui_js_file} static file")
    content = get_static_file(file_name=ui_js_file)
    try:
        return Response(
            body=content,
            status_code=200,
            headers={"Content-Type": "application/javascript; charset=utf-8"},
        )
    except Exception as ex:
        return Response(body=f"{ui_js_file} not found. {ex}", status_code=404)
コード例 #7
0
def start():
    request_body = twentyone.current_request.json_body
    if request_body:
        session = Session()
        session.start(request_body['player'], request_body['amount'])
        return Response(status_code=201,
                        headers={'Content-Type': 'application/json'},
                        body=session.state)
コード例 #8
0
def get_css():
    """Get Swagger UI CSS Endpoint

    Returns:
        str: CSS Content from Static folder
    """
    css_file = "swagger-ui.css"
    logger.info(f"Endpoint: Get CSS : {css_file} static file")
    try:
        content = get_static_file(file_name=css_file)
        return Response(
            body=content, status_code=200,
            headers={"Content-Type": "text/css"},
        )
    except Exception as ex:
        return Response(body=f"Failed request: {css_file}. {ex}",
                        status_code=404)
コード例 #9
0
def stand(sessionId):
    request_body = twentyone.current_request.json_body
    if request_body:
        session = Session(sessionId)
        session.stand()
    return Response(status_code=201,
                    headers={'Content-Type': 'application/json'},
                    body=session.state)
コード例 #10
0
    def invalid_rest_verb_response() -> Response:
        """
        A response for calling the graphql endpoint with a non POST request
        Returns:

        """
        return Response(
            body={"errors": ["GraphQL queries must be of request type POST"]},
            status_code=HTTPStatus.OK,
        )
コード例 #11
0
    def process_preflight(self, request: Request):
        """
        Preflight request support for apollo-client
        https://www.w3.org/TR/cors/#resource-preflight-requests
        """
        headers = request.headers
        origin = headers.get("Origin", "")
        method = headers.get("Access-Control-Request-Method", "").upper()

        if method and method in self.accepted_methods:
            return Response(
                status_code=200,
                headers={
                    "Access-Control-Allow-Origin":
                    origin,
                    "Access-Control-Allow-Methods":
                    ", ".join(self.accepted_methods),
                    "Access-Control-Max-Age":
                    str(self.max_age),
                },
            )
        return Response(status_code=400)
コード例 #12
0
 def invalid_query_response() -> Response:
     """
     A response for malformed queries
     Returns:
     An errors response
     """
     return Response(
         body={
             "errors":
             ["Provide a valid graphql query in the body of your request"]
         },
         status_code=HTTPStatus.OK,
     )
コード例 #13
0
def get_doc():
    """Get Swagger UI Main Page

    Returns:
        str: text/html for Swagger UI page
    """

    html = get_swagger_ui(app)
    return Response(
        body=html,
        status_code=200,
        headers={"Content-Type": "text/html"},
    )
コード例 #14
0
ファイル: app.py プロジェクト: Mappboy/PositiveBot
def get_news():
    """
    Takes in latest or random from text
    :return:
    """
    try:
        parsed = parse_qs(app.current_request.raw_body.decode())
        response = get_subscriptions_queue().send_message(
            MessageBody=json.dumps(parsed))
        if response:
            app.log.info("Message sent to queue: %s" % response)
            return Response(body='',
                            status_code=200,
                            headers={'Content-Type': 'text/plain'})
    except Exception as e:
        app.log.error(e)
        return {"text": "Something has gone wrong with the service"}
コード例 #15
0
ファイル: api.py プロジェクト: danielkemp-lab/mpc_chalice_api
def error_response(message, error_code, http_status_code, headers=None):
    body = {'Code': error_code, 'Message': message}
    response = Response(body=body, status_code=http_status_code,
                        headers=headers)

    return response.to_dict()
コード例 #16
0
def stand(sessionId):
    request_body = sevenup.current_request.json_body
    if request_body:
        session = Session(sessionId)
        # session.addCard('dealer', session.generateCard())
    return Response(status_code=201, headers={'Content-Type': 'application/json'}, body=session.state)
コード例 #17
0
def not_found() -> Response:
    return Response(status_code=404, body="Not Found", headers={},)
コード例 #18
0
def to_chalice_response(resp: BoltResponse) -> Response:
    return Response(
        status_code=resp.status, body=resp.body, headers=resp.first_headers(),
    )
コード例 #19
0
    def __call__(self, request: Request):
        try:
            data = self.parse_body(request)
            request_method = request.method.lower()
            is_graphiql = self.is_graphiql(request)
            is_pretty = self.is_pretty(request)

            # TODO: way better than if-else so better
            #  implement this too on flask and sanic
            if request_method == "options":
                return self.process_preflight(request)

            all_params: list
            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.query_params or {},
                batch_enabled=False,
                catch=is_graphiql,
                # Execute options
                run_sync=True,
                root_value=self.get_root_value(),
                context_value=self.get_context(request),
                middleware=self.get_middleware(),
            )

            result, status_code = encode_execution_results(
                execution_results,
                is_batch=False,
                format_error=self.format_error,
                encode=partial(self.encode, pretty=is_pretty),  # noqa: ignore
            )

            if is_graphiql:
                graphiql_data = GraphiQLData(
                    result=result,
                    query=getattr(all_params[0], "query"),
                    variables=getattr(all_params[0], "variables"),
                    operation_name=getattr(all_params[0], "operation_name"),
                    subscription_url=self.subscriptions,
                    headers=self.headers,
                )
                graphiql_config = GraphiQLConfig(
                    graphiql_version=self.graphiql_version,
                    graphiql_template=self.graphiql_template,
                    graphiql_html_title=self.graphiql_html_title,
                    jinja_env=self.jinja_env,
                )
                graphiql_options = GraphiQLOptions(
                    default_query=self.default_query,
                    header_editor_enabled=self.header_editor_enabled,
                    should_persist_headers=self.should_persist_headers,
                )
                source = render_graphiql_sync(data=graphiql_data,
                                              config=graphiql_config,
                                              options=graphiql_options)
                return Response(status_code=200,
                                body=source,
                                headers={'Content-Type': "text/html"})

            return Response(body=result,
                            status_code=status_code,
                            headers={'Content-Type': "application/json"})

        except HttpQueryError as err:
            parsed_error = GraphQLError(err.message)
            headers = err.headers or {}
            return Response(
                body=self.encode(
                    dict(errors=[self.format_error(parsed_error)])),
                status_code=err.status_code,
                headers={
                    **headers, 'Content-Type': "application/json"
                },
            )