Python sanic.exceptions.InvalidUsage() Examples

The following are 20 code examples of sanic.exceptions.InvalidUsage(). 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 sanic.exceptions , or try the search function .
Example #1
Source File: errors_core.py    From cape-webservices with Apache License 2.0 6 votes vote down vote up
def _500(request, exception):
    error_id = secrets.token_urlsafe(32)
    if exception.__class__ is UserException:
        debug("User exception: %s" % exception.message, exc_info=True)
        message = exception.message
    elif exception.__class__ is json.JSONDecodeError:
        debug(ERROR_INVALID_JSON, exc_info=True,error_id=error_id)
        message = ERROR_INVALID_JSON
    elif exception.__class__ is InvalidUsage :
        debug(ERROR_INVALID_USAGE, exc_info=True)
        message = ERROR_INVALID_USAGE
    else:
        warning("Exception in API", exc_info=True)
        message = ERROR_TEXT
    return jsonify({'success': False, 'result': {'message': message,'errorId':error_id}},
                   status=500, headers=generate_cors_headers(request)) 
Example #2
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def _get_output(request, id):
    if id not in request['session'].outputs or request['session'].outputs[id] is None:
        raise InvalidUsage('no such output ID')
    return request['session'].outputs[id] 
Example #3
Source File: test_plugin_exception.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def handler_1(request):
    raise InvalidUsage("OK") 
Example #4
Source File: request.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def json(self):
        if not self.parsed_json:
            try:
                self.parsed_json = json_loads(self.body)  # 解析body内容
            except Exception:
                raise InvalidUsage("Failed when parsing body as json")

        return self.parsed_json

    #
    # HTTP POST 请求, form 提交参数:
    #   - 根据 form 表单数据格式类型, 解析 form 参数
    #   - 包含 form 提交文件数据的解析
    # 
Example #5
Source File: test_blueprints.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_bp_exception_handler():
    app = Sanic('test_middleware')
    blueprint = Blueprint('test_middleware')

    @blueprint.route('/1')
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route('/2')
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route('/3')
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/1')
    assert response.status == 400


    request, response = sanic_endpoint_test(app, uri='/2')
    assert response.status == 200
    assert response.text == 'OK'

    request, response = sanic_endpoint_test(app, uri='/3')
    assert response.status == 200 
Example #6
Source File: test_exceptions.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def handler_invalid(request):
    raise InvalidUsage("OK") 
Example #7
Source File: test_exceptions_handler.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def handler_1(request):
    raise InvalidUsage("OK") 
Example #8
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def _get_connection(request, id, create_if_not_made):
    if 'uid' not in request.json:
        raise InvalidUsage('Requires "uid" field in JSON body')

    source = request['session'].uid_to_block(request.json['uid'])
    if source is None:
        raise InvalidUsage('No such item "%s"' % request.json['uid'])

    connection = _get_mixer(request, id).connection_for_source(source, create_if_not_made=create_if_not_made)
    if not connection and create_if_not_made is True:
        raise InvalidUsage('Unable to connect "%s" to mixer %d' % (request.json['uid'], id))
    return connection, request.json 
Example #9
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def _get_overlay(request, id):
    if id not in request['session'].overlays or request['session'].overlays[id] is None:
        raise InvalidUsage('no such overlay ID')
    return request['session'].overlays[id] 
Example #10
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def _get_input(request, id):
    if id not in request['session'].inputs or request['session'].inputs[id] is None:
        raise InvalidUsage('no such input ID')
    return request['session'].inputs[id] 
Example #11
Source File: test_exceptions_handler.py    From sanic with MIT License 5 votes vote down vote up
def handler_1(request):
    raise InvalidUsage("OK") 
Example #12
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def restart(request):
    if 'config' not in request.json:
        raise InvalidUsage('Body must contain "config" key')
    if request.json['config'] not in ['original', 'current']:
        raise InvalidUsage('Body "config" key must have value "original" or "current"')
    run_on_master_thread_when_idle(request['session'].end, restart=True,
                                   use_current_config=request.json['config'] == 'current')
    return _status_ok_response() 
Example #13
Source File: route_handler.py    From brave with Apache License 2.0 5 votes vote down vote up
def get_body(request, id):
    '''
    Returns the body (image contents) of a JPEG output
    '''
    output = _get_output(request, id)
    if type(output) != ImageOutput:
        raise InvalidUsage('Output is not an image')

    try:
        return await sanic.response.file_stream(
            output.location,
            headers={'Cache-Control': 'max-age=1'}
        )
    except FileNotFoundError:
        raise InvalidUsage('No such body') 
Example #14
Source File: asgi.py    From sanic with MIT License 5 votes vote down vote up
def get_websocket_connection(self) -> WebSocketConnection:
        try:
            return self._websocket_connection
        except AttributeError:
            raise InvalidUsage("Improper websocket connection.") 
Example #15
Source File: request.py    From sanic with MIT License 5 votes vote down vote up
def load_json(self, loads=json_loads):
        try:
            self.parsed_json = loads(self.body)
        except Exception:
            if not self.body:
                return None
            raise InvalidUsage("Failed when parsing body as json")

        return self.parsed_json 
Example #16
Source File: views.py    From sanic with MIT License 5 votes vote down vote up
def add(self, methods, handler, stream=False):
        if stream:
            handler.is_stream = stream
        for method in methods:
            if method not in HTTP_METHODS:
                raise InvalidUsage(f"{method} is not a valid HTTP method.")

            if method in self.handlers:
                raise InvalidUsage(f"Method {method} is already registered.")
            self.handlers[method] = handler 
Example #17
Source File: test_blueprints.py    From sanic with MIT License 5 votes vote down vote up
def test_bp_exception_handler(app):
    blueprint = Blueprint("test_middleware")

    @blueprint.route("/1")
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route("/2")
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route("/3")
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = app.test_client.get("/1")
    assert response.status == 400

    request, response = app.test_client.get("/2")
    assert response.status == 200
    assert response.text == "OK"

    request, response = app.test_client.get("/3")
    assert response.status == 200 
Example #18
Source File: test_asgi.py    From sanic with MIT License 5 votes vote down vote up
def test_improper_websocket_connection(transport, send, receive):
    with pytest.raises(InvalidUsage):
        transport.get_websocket_connection()

    transport.create_websocket_connection(send, receive)
    connection = transport.get_websocket_connection()
    assert isinstance(connection, WebSocketConnection) 
Example #19
Source File: test_views.py    From sanic with MIT License 5 votes vote down vote up
def test_composition_view_rejects_duplicate_methods():
    def foo(request):
        return text("Foo")

    view = CompositionView()

    with pytest.raises(InvalidUsage) as e:
        view.add(["GET", "POST", "GET"], foo)

    assert str(e.value) == "Method GET is already registered." 
Example #20
Source File: test_views.py    From sanic with MIT License 5 votes vote down vote up
def test_composition_view_rejects_incorrect_methods():
    def foo(request):
        return text("Foo")

    view = CompositionView()

    with pytest.raises(InvalidUsage) as e:
        view.add(["GET", "FOO"], foo)

    assert str(e.value) == "FOO is not a valid HTTP method."