Python quart.Response() Examples

The following are 17 code examples of quart.Response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module quart , or try the search function .
Example #1
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_cookie_jar() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        foo = session.get("foo")
        bar = request.cookies.get("bar")
        session["foo"] = "bar"
        response = jsonify({"foo": foo, "bar": bar})
        response.set_cookie("bar", "foo")
        return response

    client = Client(app)
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": None, "bar": None}
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": "bar", "bar": "foo"} 
Example #2
Source File: jwt_auth_callbacks.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def unauthorized_callback(error_string) -> Response:
    """
    Log that an access attempt was made without a token and return
    the result from the default callback.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "UNAUTHORISED",
        error_string=error_string,
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_unauthorized_callback(error_string) 
Example #3
Source File: jwt_auth_callbacks.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def revoked_token_callback() -> Response:
    """
    Log that an access attempt was made with a revoked token and return
    the result from the default callback.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "REVOKED_TOKEN",
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_revoked_token_callback() 
Example #4
Source File: jwt_auth_callbacks.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def invalid_token_callback(error_string) -> Response:
    """
    Log that an access attempt was made with a token that was invalid and return
    the result from the default callback.

    Parameters
    ----------
    error_string : str
        Reason the token is invalid

    Returns
    -------
    Response

    """
    current_app.access_logger.error(
        "INVALID_TOKEN",
        error_string=error_string,
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_invalid_token_callback(error_string) 
Example #5
Source File: jwt_auth_callbacks.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def claims_verification_failed_callback() -> Tuple[Dict[str, str], int]:
    """
    Log that an access attempt was made with claims that failed verification and return
    a json error message and 401 error code.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "CLAIMS_VERIFICATION_FAILED",
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return {"msg": "User claims verification failed"}, 403 
Example #6
Source File: jwt_auth_callbacks.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def expired_token_callback(expired_token: Dict[str, Any]) -> Response:
    """
    Log that an access attempt was made with an expired token and return
    the result from the default callback.

    Returns
    -------
    Response
    """

    current_app.access_logger.error(
        "EXPIRED_TOKEN",
        route=request.path,
        request_id=request.request_id,
        identity=expired_token["identity"],
        expired_token=expired_token,
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )

    return default_expired_token_callback(expired_token) 
Example #7
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_redirect_cookie_jar() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/a")
    async def a() -> Response:
        response = redirect("/b")
        response.set_cookie("bar", "foo")
        return response

    @app.route("/b")
    async def echo() -> Response:
        bar = request.cookies.get("bar")
        response = jsonify({"bar": bar})
        return response

    client = Client(app)
    response = await client.get("/a", follow_redirects=True)
    assert (await response.get_json()) == {"bar": "foo"} 
Example #8
Source File: app.py    From quart with MIT License 6 votes vote down vote up
def new_handle_http_exception(
    self: Quart, error: Union[WerkzeugHTTPException, QuartHTTPException]
) -> Response:
    if isinstance(error, WerkzeugHTTPException):
        handler = self._find_exception_handler(error)
        if handler is None:
            werkzeug_response = error.get_response()
            return await self.make_response(
                (
                    werkzeug_response.get_data(),
                    werkzeug_response.status_code,
                    werkzeug_response.headers,
                )
            )
        else:
            return await handler(error)
    else:
        return await old_handle_http_exception(self, error) 
Example #9
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_redirect() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["GET"])
    async def echo() -> str:
        return request.method

    @app.route("/redirect", methods=["GET"])
    async def redir() -> Response:
        return redirect("/")

    client = Client(app)
    assert (await client.get("/redirect", follow_redirects=True)).status_code == 200 
Example #10
Source File: app.py    From quart with MIT License 5 votes vote down vote up
def new_handle_user_exception(
    self: Quart, error: Union[Exception, WerkzeugHTTPException, QuartHTTPException]
) -> Response:
    if isinstance(error, WerkzeugHTTPException):
        return await new_handle_http_exception(self, error)
    else:
        return await old_handle_user_exception(self, error) 
Example #11
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_query_string() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        data = request.args
        return jsonify(**data)

    client = Client(app)
    response = await client.get("/", query_string={"a": "b"})
    assert (await response.get_json()) == {"a": "b"} 
Example #12
Source File: home.py    From async-techniques-python-course with MIT License 5 votes vote down vote up
def not_found(_):
    return quart.Response("The page was not found.", status=404) 
Example #13
Source File: __init__.py    From aiocqhttp with MIT License 5 votes vote down vote up
def _handle_http_event(self) -> Response:
        if self._secret:
            if 'X-Signature' not in request.headers:
                self.logger.warning('signature header is missed')
                abort(401)

            sec = self._secret
            sec = sec.encode('utf-8') if isinstance(sec, str) else sec
            sig = hmac.new(sec, await request.get_data(), 'sha1').hexdigest()
            if request.headers['X-Signature'] != 'sha1=' + sig:
                self.logger.warning('signature header is invalid')
                abort(403)

        payload = await request.json
        if not isinstance(payload, dict):
            abort(400)

        if request.headers['X-Self-ID'] in self._wsr_api_clients:
            self.logger.warning(
                'there is already a reverse websocket api connection, '
                'so the event may be handled twice.')

        response = await self._handle_event(payload)
        if isinstance(response, dict):
            return jsonify(response)
        return Response('', 204) 
Example #14
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_data() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["POST"])
    async def echo() -> Response:
        data = await request.get_data(True)
        return data

    client = Client(app)
    headers = {"Content-Type": "application/octet-stream"}
    response = await client.post("/", data=b"ABCDEFG", headers=headers)
    assert (await response.get_data(True)) == b"ABCDEFG"  # type: ignore 
Example #15
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_json() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["POST"])
    async def echo() -> Response:
        data = await request.get_json()
        return jsonify(data)

    client = Client(app)
    response = await client.post("/", json={"a": "b"})
    assert (await response.get_json()) == {"a": "b"} 
Example #16
Source File: test_exceptions.py    From quart with MIT License 5 votes vote down vote up
def test_abort_with_response() -> None:
    with pytest.raises(HTTPException) as exc_info:
        abort(Response("Message", 205))
    assert exc_info.value.get_response().status_code == 205 
Example #17
Source File: test_basic.py    From quart with MIT License 5 votes vote down vote up
def test_make_response_response(app: Quart) -> None:
    response = await app.make_response(Response("Result"))
    assert response.status_code == 200
    assert (await response.get_data()) == b"Result"  # type: ignore

    response = await app.make_response((Response("Result"), {"name": "value"}))
    assert response.status_code == 200
    assert (await response.get_data()) == b"Result"  # type: ignore
    assert response.headers["name"] == "value"

    response = await app.make_response((Response("Result"), 404, {"name": "value"}))
    assert response.status_code == 404
    assert (await response.get_data()) == b"Result"  # type: ignore
    assert response.headers["name"] == "value"