Пример #1
0
    def on_post(self):
        command = AddItemCommand({
            **flask.request.json, 'seller_id': g.user_id
        },
                                 strict=False)
        command_name = type(command).__name__

        import pdb
        pdb.set_trace()
        if not command.is_valid():
            flask.abort(
                Response(json_response({
                    'title':
                    'Invalid Command',
                    'description':
                    f'{command_name} validation failed due to {command.validation_errors()}'
                }),
                         status=HTTPStatus.BAD_REQUEST))

        try:
            result = self._command_bus.execute(command)
            return json_response(result), HTTPStatus.OK
        except Exception as e:
            flask.abort(
                Response(json_response({
                    'title': f'Failed to execute {command_name}',
                    'description': str(e)
                }),
                         status=HTTPStatus.BAD_REQUEST))
Пример #2
0
async def vehicle_configuration_handler(request):
    pk = int(request.match_info.get('vehicle_id'))
    vehicle_functions = await VehicleFunctions.fetch_many(
        filter_by={'vehicle_id': pk})
    features_ids = [idx for item in vehicle_functions for idx in item.features]
    connections_ids = [idx for item in vehicle_functions
                       for idx in item.connections]
    function_ids = [v.function_id for v in vehicle_functions]

    connections = await VehicleConnections.fetch_by_ids(connections_ids)
    features = await Feature.fetch_by_ids(features_ids)
    functions = await Function.fetch_by_ids(function_ids)

    components_ids = [c.component_id for c in connections]
    interfaces_ids = [c.interface_id for c in connections]

    components = await Component.fetch_by_ids(components_ids)
    interfaces = await Interface.fetch_by_ids(interfaces_ids)

    result = {
        'data': vehicle_functions_schema.dump(
            vehicle_functions, many=True).data,
        'included': {
            'features': feature_schema.dump(features, many=True).data,
            'functions': function_schema.dump(functions, many=True).data,
            'components': component_schema.dump(components, many=True).data,
            'interfaces': interface_schema.dump(interfaces, many=True).data,
        }
    }
    return json_response(result)
Пример #3
0
 def on_get(self, req, res):
     doc = {
         'framework': 'Falcon {}'.format(falcon.__version__),
         'application': APPLICATION_NAME,
     }
     res.body = json_response(doc)
     res.status = falcon.HTTP_200
Пример #4
0
 def on_get(self):
     doc = {
         'framework': 'Flask {}'.format(flask.__version__),
         'application': APPLICATION_NAME,
     }
     body = json_response(doc)
     status = HTTPStatus.OK
     return body, status
Пример #5
0
async def vehicle_item_handler(request):
    pk = int(request.match_info.get('vehicle_id'))
    vehicle = await Vehicle.fetch_one(pk)
    properties = await VehicleProperty.fetch_by_ids(vehicle.properties)

    result = {
        'data': vehicle_schema.dump(vehicle).data,
        'included': vehicle_property_schema.dump(properties, many=True).data
    }
    return json_response(result)
Пример #6
0
def test_custom_json_encoder_for_complex_object_with_dict():
    data = {
        'complex_json': MockComplexObjectWithDictMethod('title', 'some text for __dict__', 12.34),
    }
    expected = '{"complex_json": {"desc": "some text for __dict__", "title": "title", "value": 12.34}}'

    actual = CustomJSONEncoder().encode(data)
    json_response_value = json_response(data)
    assert actual == expected
    assert json_response_value == expected
Пример #7
0
def test_custom_json_encoder_for_object_with_dict():
    data = {
        'mock_object_dict': MockObjectWithDictMethod('some text for __dict__'),
    }
    expected = '{"mock_object_dict": {"desc": "some text for __dict__"}}'

    actual = CustomJSONEncoder().encode(data)
    json_response_value = json_response(data)
    assert actual == expected
    assert json_response_value == expected
Пример #8
0
def test_custom_json_encoder_for_object_with_to_json_method():
    data = {
        'mock_object_to_json': MockObjectWithToJsonMethod('some text for to_json')
    }
    expected = '{"mock_object_to_json": {"desc": "some text for to_json"}}'

    actual = CustomJSONEncoder().encode(data)
    json_response_value = json_response(data)
    assert actual == expected
    assert json_response_value == expected
Пример #9
0
    def on_get(self, req, res):
        query = GetItemsQuery()
        if not query.is_valid():
            res.status = falcon.HTTP_400
            # TODO: Add error details
            return

        result = self._query_bus.execute(query)
        res.body = json_response(result)
        res.status = falcon.HTTP_200
Пример #10
0
    def on_get(self):
        query = GetItemsQuery()
        if not query.is_valid():
            # TODO: Add error details
            return '', HTTPStatus.BAD_REQUEST

        result = self._query_bus.execute(query)
        body = json_response(result)
        status = HTTPStatus.OK
        return body, status
Пример #11
0
async def vehicle_list_handler(request):
    vehicles = await Vehicle.fetch_many()
    property_idx = [idx for v in vehicles for idx in v.properties]
    properties = await VehicleProperty.fetch_by_ids(property_idx)

    result = {
        'data': vehicle_schema.dump(vehicles, many=True).data,
        'included': {
            'properties': vehicle_property_schema.dump(properties, many=True).data,
        }
    }
    return json_response(result)
Пример #12
0
    def authenticate(self):
        if request.headers.get('Authorization') is None:
            abort(Response(json_response({
                'title': 'Authentication failed',
                'description': 'Authorization header is missing'
            }), status=HTTPStatus.UNAUTHORIZED))

        try:
            auth_type, credentials = request.headers['Authorization'].split(' ')
        except Exception:
            abort(Response(json_response({
                'title': 'Authentication failed',
                'description': "Wrong Authentication header"
            })))

        if auth_type.lower() != 'basic':
            abort(Response(json_response({
                'title': 'Authentication failed',
                'description': "Expected 'Authorization: Basic <credentials>' header"
            }), status=HTTPStatus.UNAUTHORIZED))

        try:
            decoded_credentials = base64.b64decode(credentials)
            login, password = decoded_credentials.decode().split(':')
        except Exception as e:
            abort(Response(json_response({
                'title': 'Authentication failed',
                'description': f'Invalid credentials ({e})'
            }), status=HTTPStatus.UNAUTHORIZED))

        user = self._users_repository.get_user_by_login_and_password(login, password)

        if user is None:
            abort(Response(json_response({
                'title': 'Authentication failed',
                'description': 'Invalid credentials'
            }), status=HTTPStatus.UNAUTHORIZED))

        return user
Пример #13
0
def test_custom_json_encoder_for_date():
    current_date = datetime.now()
    data = {
        'date': current_date,
    }
    expected = (
        '{'
        f"\"date\": \"{current_date.isoformat() + 'Z'}\""
        '}'
    )

    actual = CustomJSONEncoder().encode(data)
    json_response_value = json_response(data)
    assert actual == expected
    assert json_response_value == expected
Пример #14
0
async def group_list_handler(request):
    groups = await Group.fetch_many()
    features_ids = [idx for g in groups for idx in g.features]
    features = await Feature.fetch_by_ids(features_ids)
    functions_ids = [idx for f in features for idx in f.functions]
    functions = await Function.fetch_by_ids(functions_ids)

    result = {
        'data': group_schema.dump(groups, many=True).data,
        'included': {
            'features': feature_schema.dump(features, many=True).data,
            'functions': function_schema.dump(functions, many=True).data,
        }
    }
    return json_response(result)
Пример #15
0
    def on_post(self, req, res):
        command = AddItemCommand(
            {
                **req.media, 'seller_id': req.context['user_id']
            }, strict=False)
        command_name = type(command).__name__

        if not command.is_valid():
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title='Invalid command',
                description="{} validation failed due to {}".format(
                    command_name, command.validation_errors()))

        try:
            result = self._command_bus.execute(command)
            res.status = falcon.HTTP_200
            res.body = json_response(result)
        except Exception as e:
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title='Failed to execute {}'.format(command_name),
                description=str(e))
Пример #16
0
async def internal_error_handler(request, exc):
    payload = {
        'error': 'Internal Error',
    }
    return json_response(payload, status=getattr(exc, 'status', 500))
Пример #17
0
async def root_handler(request):
    payload = {
        'data': 'vehicle builder api',
    }
    return json_response(payload)
Пример #18
0
async def not_found_handler(request, exc):
    payload = {
        'error': 'Not Found',
    }
    return json_response(payload, status=exc.status)