def test_marshal_with_handle_polymorph(self, app, client):
        api = Api(app)

        parent = api.model('Person', {
            'name': fields.String,
        })

        child1 = api.inherit('Child1', parent, {
            'extra1': fields.String,
        })

        child2 = api.inherit('Child2', parent, {
            'extra2': fields.String,
        })

        class Child1(object):
            name = 'child1'
            extra1 = 'extra1'

        class Child2(object):
            name = 'child2'
            extra2 = 'extra2'

        mapping = {
            Child1: child1,
            Child2: child2
        }

        thing = api.model('Thing', {
            'owner': fields.Polymorph(mapping),
        })

        @api.route('/thing-1/')
        class Thing1Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child1()}

        @api.route('/thing-2/')
        class Thing2Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child2()}

        data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child1'}}

        data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{extra1}'})
        assert data == {'owner': {'extra1': 'extra1'}}

        data = client.get_json('/thing-2/', headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child2'}}
Beispiel #2
0
    def test_marshal_with_handle_polymorph(self, app, client):
        api = Api(app)

        parent = api.model('Person', {
            'name': fields.String,
        })

        child1 = api.inherit('Child1', parent, {
            'extra1': fields.String,
        })

        child2 = api.inherit('Child2', parent, {
            'extra2': fields.String,
        })

        class Child1(object):
            name = 'child1'
            extra1 = 'extra1'

        class Child2(object):
            name = 'child2'
            extra2 = 'extra2'

        mapping = {Child1: child1, Child2: child2}

        thing = api.model('Thing', {
            'owner': fields.Polymorph(mapping),
        })

        @api.route('/thing-1/')
        class Thing1Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child1()}

        @api.route('/thing-2/')
        class Thing2Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child2()}

        data = client.get_json('/thing-1/',
                               headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child1'}}

        data = client.get_json('/thing-1/',
                               headers={'X-Fields': 'owner{extra1}'})
        assert data == {'owner': {'extra1': 'extra1'}}

        data = client.get_json('/thing-2/',
                               headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child2'}}
    def test_marshal_handle_inheritance(self):
        api = Api(self.app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = api.inherit('Child', person, {
            'extra': fields.String,
        })

        data = {
            'name': 'John Doe',
            'age': 42,
            'extra': 'extra'
        }

        values = (
            ('name', {'name': 'John Doe'}),
            ('name,extra', {'name': 'John Doe', 'extra': 'extra'}),
            ('extra', {'extra': 'extra'}),
        )

        for mask, expected in values:
            result = marshal(data, child, mask=mask)
            self.assertEqual(result, expected)
    def test_list_fields_with_nested_inherited(self):
        api = Api(self.app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer
        })
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'children': fields.List(fields.Nested(child))
        })

        result = mask.apply(family.resolved, 'children{name,attr}')

        data = {'children': [
            {'name': 'John', 'age': 5, 'attr': 'value-john'},
            {'name': 'Jane', 'age': 42, 'attr': 'value-jane'},
        ]}
        expected = {'children': [
            {'name': 'John', 'attr': 'value-john'},
            {'name': 'Jane', 'attr': 'value-jane'},
        ]}

        self.assertDataEqual(marshal(data, result), expected)
        # Should leave th original mask untouched
        self.assertDataEqual(marshal(data, family), data)
Beispiel #5
0
    def test_marshal_handle_inheritance(self, app):
        api = Api(app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = api.inherit('Child', person, {
            'extra': fields.String,
        })

        data = {'name': 'John Doe', 'age': 42, 'extra': 'extra'}

        values = (
            ('name', {
                'name': 'John Doe'
            }),
            ('name,extra', {
                'name': 'John Doe',
                'extra': 'extra'
            }),
            ('extra', {
                'extra': 'extra'
            }),
        )

        for value, expected in values:
            result = marshal(data, child, mask=value)
            assert result == expected
    def test_marshal_with_honour_complex_field_mask_header(self):
        api = Api(self.app)

        person = api.model('Person', person_fields)
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'father': fields.Nested(person),
            'mother': fields.Nested(person),
            'children': fields.List(fields.Nested(child)),
            'free': fields.List(fields.Raw),
        })

        house = api.model('House', {
            'family': fields.Nested(family, attribute='people')
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(house)
            def get(self):
                return {'people': {
                    'father': {'name': 'John', 'age': 42},
                    'mother': {'name': 'Jane', 'age': 42},
                    'children': [
                        {'name': 'Jack', 'age': 5, 'attr': 'value-1'},
                        {'name': 'Julie', 'age': 7, 'attr': 'value-2'},
                    ],
                    'free': [
                        {'key-1': '1-1', 'key-2': '1-2'},
                        {'key-1': '2-1', 'key-2': '2-2'},
                    ]
                }}

        data = self.get_json('/test/', headers={
            'X-Fields': 'family{father{name},mother{age},children{name,attr},free{key-2}}'
        })
        expected = {'family': {
            'father': {'name': 'John'},
            'mother': {'age': 42},
            'children': [{'name': 'Jack', 'attr': 'value-1'}, {'name': 'Julie', 'attr': 'value-2'}],
            'free': [{'key-2': '1-2'}, {'key-2': '2-2'}]
        }}
        self.assertEqual(data, expected)
Beispiel #7
0
    def test_list_fields_with_nested_inherited(self, app):
        api = Api(app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer
        })
        child = api.inherit('Child', person, {'attr': fields.String})

        family = api.model('Family',
                           {'children': fields.List(fields.Nested(child))})

        result = mask.apply(family.resolved, 'children{name,attr}')

        data = {
            'children': [
                {
                    'name': 'John',
                    'age': 5,
                    'attr': 'value-john'
                },
                {
                    'name': 'Jane',
                    'age': 42,
                    'attr': 'value-jane'
                },
            ]
        }
        expected = {
            'children': [
                {
                    'name': 'John',
                    'attr': 'value-john'
                },
                {
                    'name': 'Jane',
                    'attr': 'value-jane'
                },
            ]
        }

        assert_data(marshal(data, result), expected)
        # Should leave th original mask untouched
        assert_data(marshal(data, family), data)
Beispiel #8
0
        description='Name of the submitted task',
        example='doSomething',
    )),
    ('taskId', fields.String(
        required=True,
        description='ID of the created task',
        example='942b3fb5-fe63-49cd-9b6d-230c36070d8f',
    )),
]))

taskResponseModel = api.inherit('taskResponse', taskInfoModel, OrderedDict([
    ('statusUrl', fields.String(
        required=True,
        description='URL to receive the status of the task',
        example='/status/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8f',
    )),
    ('statusStreamUrl', fields.String(
        description='URL to receive a stream of the task status',
        example='/statusStream/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8',
    )),
]))

taskStateModel = api.model('taskState', OrderedDict([
    ('state', fields.String(
        required=True,
        description='Celery state of the job',
        example='STARTED',
    )),
    ('info', fields.Raw(
        required=True,
        description='Data related to its execution',
Beispiel #9
0
        ('taskId',
         fields.String(
             required=True,
             description='ID of the created task',
             example='942b3fb5-fe63-49cd-9b6d-230c36070d8f',
         )),
    ]))

taskResponseModel = api.inherit(
    'taskResponse', taskInfoModel,
    OrderedDict([
        ('statusUrl',
         fields.String(
             required=True,
             description='URL to receive the status of the task',
             example='/status/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8f',
         )),
        ('statusStreamUrl',
         fields.String(
             description='URL to receive a stream of the task status',
             example=
             '/statusStream/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8',
         )),
    ]))

taskStateModel = api.model(
    'taskState',
    OrderedDict([
        ('state',
         fields.String(
             required=True,
             description='Celery state of the job',
Beispiel #10
0

# Specifications of the objects accepted/returned by the API.
AppName = api.model('App name', {
    'name': fields.String(required=True,
                          description='App name',
                          example="My App"),
})

AppData = api.model('App data', {
    'data': fields.Raw(required=True,
                       description='App data',
                       example={"any_data": "you_like_goes_here"}),
})

AppWithData = api.inherit('App with data',  AppData, AppName)


@schema_ns.route('')
class SchemaResource(Resource):
    """Resource allowing access to the OpenAPI schema for the entire API."""

    def get(self):
        """
        Return the OpenAPI schema.
        """
        log.debug("Generating schema")
        return api.__schema__


@apps_ns.route('')
Beispiel #11
0
            },
            'raw': [{}, 3],
            'values': {},
            'weight': 19.2,
        }


_task_model = api.model('', {
    'id': fields.Integer(),
    'task': fields.String(),
})
# 继承语法, 注意使用(namespace也有inherit语法)
# orderer: 确保返回值的位置跟定义的位置保持一致, 这样会有一定的损耗.
# 该用法在: Api, Namespace, marsha1中都可以使用
order_model = api.inherit('order', _task_model, {
    'desc': fields.String(),
})


@api.route('/todo/order', endpoint='order_ep')
class TodoOrder(Resource):
    def get(self):
        # 利用order确保返回顺序和定义是一致的(和model中定义一致)
        v = {
            'id': 3,
            'task': 'format task',
            'desc': '冗余数据',
        }
        return api.marshal(v, order_model, ordered=True)

Beispiel #12
0
    description='API for School API services',
    ordered=True,
)

school = school_swagger.model(
    'actionCreateRequest', {
        'district': fields.String(),
        'block': fields.String(),
        'cluster': fields.String(),
        'schoolid': fields.String(),
        'schoolname': fields.String(),
        'category': fields.String(),
        'gender': fields.String(),
        'medium_of_inst': fields.String(),
        'area': fields.String(),
        'pincode': fields.String(),
        'landmark': fields.String(),
    })

response = school_swagger.model(
    'pythonBaseResponse', {
        'applicationCode': fields.Integer(),
        'code': fields.Integer(),
        'message': fields.String(),
        'status': fields.String()
    })

schoolBaseResponse = school_swagger.inherit(
    'schoolBaseResponse', response,
    {'schoolDetails': fields.List(fields.Nested(school))})
def create_app(env_name):
    """
  Create application
  """
    # app initiliazation
    app = Flask(__name__)

    app.config.from_object(app_config[env_name])
    app.url_map.converters['list'] = ListConverter

    # initializing bcrypt and db
    bcrypt.init_app(app)
    db.init_app(app)
    api = Api(app,
              default='ManagementServer',
              default_label='This is the ManagementServer service',
              version='0.0.1',
              title='ManagementServer API with Python',
              description='API for ICP OpsAuto services',
              ordered=True)
    managementServerSchema = api.model(
        'managementServerSchema', {
            'loggedInUser':
            fields.String(required=True, description='The loggedInUser'),
            'mgmtServerCommonName':
            fields.String(required=False,
                          description='The mgmtServerCommonName'),
            'mgmtServerHostName':
            fields.String(description='The mgmtServerHostName'),
            'mgmtServerFQDN':
            fields.String(description='mgmtServerFQDN'),
            'mgmtServerIPAddress':
            fields.String(description='mgmtServerIPAddress'),
            'oSCredentialId':
            fields.Integer(dump_only=True),
            'appCredentialId1':
            fields.Integer(dump_only=True),
            'appCredentialId2':
            fields.Integer(dump_only=True),
            'appCredentialId3':
            fields.Integer(dump_only=True),
            'appCredentialId4':
            fields.Integer(dump_only=True),
            'mgmtServerIPV6':
            fields.String(description='mgmtServerIPV6'),
            'mgmtServerDesc':
            fields.String(description='mgmtServerDesc'),
            'mgmtServerRemarks':
            fields.String(description='mgmtServerRemarks'),
            'mgmtServerIsActive':
            fields.Boolean(description='mgmtServerIsActive', required=True)
        })

    managementServerPut = api.model(
        'managementServerPut', {
            'loggedInUser':
            fields.String(required=True, description='The loggedInUser'),
            'mgmtServerCommonName':
            fields.String(required=False,
                          description='The mgmtServerCommonName'),
            'mgmtServerHostName':
            fields.String(description='The mgmtServerHostName'),
            'mgmtServerFQDN':
            fields.String(description='mgmtServerFQDN'),
            'mgmtServerIPAddress':
            fields.String(description='mgmtServerIPAddress'),
            'oSCredentialId':
            fields.Integer(dump_only=True),
            'appCredentialId1':
            fields.Integer(dump_only=True),
            'appCredentialId2':
            fields.Integer(dump_only=True),
            'appCredentialId3':
            fields.Integer(dump_only=True),
            'appCredentialId4':
            fields.Integer(dump_only=True),
            'mgmtServerIPV6':
            fields.String(description='mgmtServerIPV6'),
            'mgmtServerDesc':
            fields.String(description='mgmtServerDesc'),
            'mgmtServerRemarks':
            fields.String(description='mgmtServerRemarks')
        })
    managementServer = api.model(
        'managementServer', {
            'loggedInUser':
            fields.String(required=True, description='The loggedInUser'),
            'mgmtServerCommonName':
            fields.String(required=False,
                          description='The mgmtServerCommonName'),
            'mgmtServerHostName':
            fields.String(description='The mgmtServerHostName'),
            'mgmtServerFQDN':
            fields.String(description='mgmtServerFQDN'),
            'mgmtServerIPAddress':
            fields.String(description='mgmtServerIPAddress'),
            'oSCredentialId':
            fields.Integer(dump_only=True),
            'appCredentialId1':
            fields.Integer(dump_only=True),
            'appCredentialId2':
            fields.Integer(dump_only=True),
            'appCredentialId3':
            fields.Integer(dump_only=True),
            'appCredentialId4':
            fields.Integer(dump_only=True),
            'mgmtServerIPV6':
            fields.String(description='mgmtServerIPV6'),
            'mgmtServerDesc':
            fields.String(description='mgmtServerDesc'),
            'mgmtServerRemarks':
            fields.String(description='mgmtServerRemarks'),
            'mgmtServerIsActive':
            fields.Boolean(description='mgmtServerIsActive', required=True)
        })

    managementServerBaseResponse = api.model(
        'managementServerBaseResponse', {
            'applicationCode': fields.Integer(),
            'code': fields.Integer(),
            'message': fields.String(),
            'status': fields.String()
        })

    managementServerResponse = api.inherit(
        'managementServerResponse', managementServerBaseResponse, {
            'managementServer': fields.List(
                fields.Nested(managementServerSchema))
        })

    @api.route('/managementServers/<list:mgmtServerId>')
    class ManagementServerByIds(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(params={'mgmtServerId': 'mgmtServerId'},
                 responses={
                     400: 'ERROR',
                     500: 'SERVER_ERROR'
                 },
                 description='Get managementServer by Ids')
        def get(self, mgmtServerId):
            return mgmtserverimplementation.get_mgmtserver_by_ids(mgmtServerId)

    @api.route(
        '/managementServers/mgmtServerCommonNames/<mgmtServerCommonName>')
    class ManagementServerByIds(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(params={'mgmtServerCommonName': 'mgmtServerCommonName'},
                 responses={
                     400: 'ERROR',
                     500: 'SERVER_ERROR'
                 },
                 description='Get managementServer by Ids')
        def get(self, mgmtServerCommonName):
            return mgmtserverimplementation.get_mgmtserver_by_name(
                mgmtServerCommonName)

    @api.route('/managementServers/<int:mgmtServerId>')
    class ManagementServerUpdate(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(params={'mgmtServerId': 'mgmtServerId'},
                 responses={
                     400: 'ERROR',
                     500: 'SERVER_ERROR'
                 },
                 description='Get managementServer by Ids')
        @api.expect(managementServer)
        def put(self, mgmtServerId):
            return mgmtserverimplementation.update_managementserver(
                mgmtServerId)

    @api.route('/managementServers')
    class ManagementServerCreation(Resource):
        @api.response(201, 'CREATED', managementServerResponse)
        @api.doc(responses={
            400: 'ERROR',
            500: 'SERVER_ERROR'
        },
                 description='create a management server')
        @api.expect(managementServerPut)
        def post(self):
            print("this is post")
            return mgmtserverimplementation.mgmtserver_creation()

    @api.route('/managementServers/allManagementServers')
    class AllResourceTypes(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(responses={
            400: 'ERROR',
            500: 'SERVER_ERROR'
        },
                 description='Get managementServer by Ids')
        def get(self):
            return mgmtserverimplementation.get_all_managementservers()

    @api.route('/managementServers/allActiveManagementServers')
    class AllActiveManagementServers(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(
            responses={
                400: 'ERROR',
                500: 'SERVER_ERROR'
            }, )
        def get(self):
            return mgmtserverimplementation.get_all_activemanagementservers()

    @api.route('/managementServers/<int:mgmtServerId>/<loggedInUser>')
    class ResourceType(Resource):
        @api.response(200, 'OK', managementServerResponse)
        @api.doc(params={
            'mgmtServerId': 'An ID',
            'loggedInUser': '******'
        },
                 responses={
                     400: 'ERROR',
                     500: 'SERVER_ERROR'
                 },
                 description='Get mgmtServer by Ids')
        def delete(self, mgmtServerId, loggedInUser):
            return mgmtserverimplementation.deleteManagementServer(
                mgmtServerId, loggedInUser)

    return app
Beispiel #14
0

def create_id():
    return str(uuid.uuid4())


# Models and validation for input/output fields
product_input_fields = api.model(
    'ProductInput', {
        'title': fields.String(required=True),
        'price': fields.Float(required=True, min=0),
        'inventory_count': fields.Integer(required=True, min=0)
    })

product_fields = api.inherit('Product', product_input_fields, {
    'id': fields.String(required=True),
})

pagination = api.model(
    'A page of results', {
        'page': fields.Integer(description='Number of this page of results'),
        'pages':
        fields.Integer(description='Total number of pages of results'),
    })

page_of_products = api.inherit(
    'Page of products', pagination,
    {'items': fields.List(fields.Nested(product_fields))})

cart_fields = api.model(
    'Cart', {
Beispiel #15
0
    def __init__(self, db_file, secret_token, smtp_context):

        service = Flask(__name__)
        service_api = Api(app=service)
        name_space = service_api.namespace('',
                                           description="Event Manager API",
                                           version="1.0",
                                           title="Event Manager")
        db_file = db_file
        self.service = service

        event_model = service_api.model(
            'Event', {
                'name':
                fields.String(description='The name of the event',
                              required=True),
                'location':
                fields.String(description='The address of the event',
                              required=True),
                'start_timestamp':
                fields.String(
                    description=
                    'Start date of the event in UTC. format:YYYY-MM-DD HH:MM:SS',
                    required=True),
                'end_timestamp':
                fields.String(
                    description=
                    'End date of the event in UTC. format:YYYY-MM-DD HH:MM:SS',
                    required=True)
            })

        user_model = service_api.model('User', {
            'email':
            fields.String(description='Email of the user', required=True)
        })

        event_added_response = service_api.model(
            'EventAddedResponse', {
                "event_id":
                fields.String(description="unique identifer of the event",
                              required=True)
            })

        event_with_metadata = service_api.inherit(
            'EventWithMetaData', event_model, {
                "id":
                fields.String(description="unique identifer of the event",
                              required=True)
            })

        @name_space.route('/events')
        class Events(Resource):
            @service_api.response(200,
                                  'List of events successfully retrieved',
                                  model=[event_with_metadata])
            @service_api.response(500, 'Database error')
            @service_api.doc(description="List all events")
            @service_api.marshal_with(event_with_metadata)
            def get(self):
                conn = database.open_connection(db_file)
                with conn:
                    return database.list_events(conn), 200
                abort(500)

            @service_api.response(200,
                                  'New event added successfully',
                                  model=event_added_response)
            @service_api.response(400, 'Invalid event parameters')
            @service_api.response(500, 'Database error')
            @service_api.doc(expect=[event_model],
                             description="Add a new event")
            @service_api.marshal_with(event_added_response)
            def post(self):
                conn = database.open_connection(db_file)
                with conn:
                    try:
                        event_id = database.add_event_from_json(
                            conn, request.json)
                        return {'event_id': event_id}, 200
                    except:
                        abort(400)
                abort(500)

        @name_space.route('/event/<event_id>')
        class Event(Resource):
            @service_api.doc(params={'event_id': 'Event unique identifier'},
                             description="Get event data from its ID")
            @service_api.response(200,
                                  'Event data retrieved successfully',
                                  model=event_with_metadata)
            @service_api.response(500, 'Database error')
            @service_api.marshal_with(event_with_metadata)
            def get(self, event_id):
                conn = database.open_connection(db_file)
                with conn:
                    try:
                        return database.get_event(conn, event_id), 200
                    except:
                        abort(400)
                abort(500)

            @service_api.doc(params={'event_id': 'Event unique identifier'},
                             description="Delete an event")
            @service_api.response(200, 'Event deleted successfully')
            @service_api.response(400, 'Non existing event id')
            @service_api.response(500, 'Database error')
            def delete(self, event_id):
                conn = database.open_connection(db_file)
                with conn:
                    try:
                        database.delete_event(conn, event_id)
                        return {}
                    except database.NonExistingError:
                        abort(400)
                abort(500)

        @name_space.route('/users/<user_email>')
        class list_user_events(Resource):
            @service_api.doc(
                params={'user_email': 'Email address used to register events'},
                description="List all the events registered by a user")
            @service_api.response(200,
                                  'Users\' events retrieved successfully',
                                  model=[event_with_metadata])
            @service_api.response(500, 'Database error')
            @service_api.marshal_with(event_with_metadata)
            def get(self, user_email):
                conn = database.open_connection(db_file)
                with conn:
                    return database.list_user_events(conn, user_email), 200
                abort(500)

        @name_space.route('/register/<user_email>/<event_id>')
        class register_user(Resource):
            @service_api.doc(params={
                'user_email': 'Email address to add to the event',
                'event_id': 'Event unique identifier'
            },
                             description="Register an user to an event")
            @service_api.response(200,
                                  'User successfully registered to the event')
            @service_api.response(400, 'Non existing event id')
            @service_api.response(500, 'Database error')
            def post(self, user_email, event_id):
                conn = database.open_connection(db_file)
                with conn:
                    # Automatically register user in DB
                    try:
                        database.register_user(conn, user_email, event_id)
                    except database.DuplicateError:
                        # Ignore if duplicate
                        pass
                    try:
                        database.register_event(conn, user_email, event_id)
                        event = database.get_event(conn, event_id)
                        email_utils.send_notification(smtp_context, user_email,
                                                      event_id)
                        email_utils.send_calendar_invite(
                            smtp_context, user_email, event)
                    except database.NonExistingError:
                        name_space.abort(400)
                    except database.DuplicateError:
                        # Ignore if duplicate
                        pass
                    return {}
                abort(500)

            @service_api.doc(params={
                'user_email': 'Email address used to unregister events',
                'event_id': 'Event unique identifier'
            },
                             description="Unregister an user from an event")
            @service_api.response(
                200, 'User successfully unregistered from the event')
            @service_api.response(400, 'Non existing event id')
            @service_api.response(500, 'Database error')
            def delete(self, user_email, event_id):
                conn = database.open_connection(db_file)
                with conn:
                    try:
                        database.unregister_event(conn, user_email, event_id)
                    except database.NonExistingError:
                        abort(400)
                    return {}
                abort(500)

        @name_space.route('/admin/<token>/<event_id>')
        class Admin(Resource):
            @service_api.doc(params={
                'token': 'Secret token',
                'event_id': 'Event unique identifier'
            },
                             description="Register an user to an event")
            @service_api.response(200,
                                  'List of users successfully retrieved',
                                  model=[user_model])
            @service_api.response(401, 'Unauthorized')
            @service_api.response(400, 'Event does not exist')
            @service_api.response(500, 'Database error')
            @service_api.doc(description="List all users going to an event")
            @service_api.marshal_with(user_model)
            def get(self, token, event_id):
                conn = database.open_connection(db_file)
                if token != secret_token:
                    abort(401)
                with conn:
                    try:
                        return database.get_users_attending_event(
                            conn, event_id), 200
                    except database.NonExistingError:
                        abort(400)
                abort(500)
Beispiel #16
0
class ModelTestCase(TestCase):
    def setUp(self):
        super(ModelTestCase, self).setUp()
        blueprint = Blueprint('api', __name__)
        self.api = Api(blueprint)
        self.app.register_blueprint(blueprint)

    def test_model_as_flat_dict(self):
        model = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        self.assertEqual(model.__schema__, {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                }
            }
        })

    def test_model_as_nested_dict(self):
        address = self.api.model('Address', {
            'road': fields.String,
        })

        person = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
            'address': fields.Nested(address)
        })

        self.assertEqual(person.__schema__, {
            # 'required': ['address'],
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'address': {
                    '$ref': '#/definitions/Address',
                }
            }
        })

        self.assertEqual(address.__schema__, {
            'properties': {
                'road': {
                    'type': 'string'
                },
            }
        })

    def test_model_as_dict_with_list(self):
        model = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'tags': fields.List(fields.String),
        })

        self.assertEqual(model.__schema__, {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'tags': {
                    'type': 'array',
                    'items': {
                        'type': 'string'
                    }
                }
            }
        })

    def test_model_as_nested_dict_with_list(self):
        address = self.api.model('Address', {
            'road': fields.String,
        })

        person = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
            'addresses': fields.List(fields.Nested(address))
        })

        self.assertEqual(person.__schema__, {
            # 'required': ['address'],
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'addresses': {
                    'type': 'array',
                    'items': {
                        '$ref': '#/definitions/Address',
                    }
                }
            }
        })

        self.assertEqual(address.__schema__, {
            'properties': {
                'road': {
                    'type': 'string'
                },
            }
        })

    def test_model_with_required(self):
        model = self.api.model('Person', {
            'name': fields.String(required=True),
            'age': fields.Integer,
            'birthdate': fields.DateTime(required=True),
        })

        self.assertEqual(model.__schema__, {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                }
            },
            'required': ['birthdate', 'name']
        })

    def test_model_as_nested_dict_and_required(self):
        address = self.api.model('Address', {
            'road': fields.String,
        })

        person = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
            'address': fields.Nested(address, required=True)
        })

        self.assertEqual(person.__schema__, {
            'required': ['address'],
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'address': {
                    '$ref': '#/definitions/Address',
                }
            }
        })

        self.assertEqual(address.__schema__, {
            'properties': {
                'road': {
                    'type': 'string'
                },
            }
        })

    def test_model_with_discriminator(self):
        model = self.api.model('Person', {
            'name': fields.String(discriminator=True),
            'age': fields.Integer,
        })

        self.assertEqual(model.__schema__, {
            'properties': {
                'name': {'type': 'string'},
                'age': {'type': 'integer'},
            },
            'discriminator': 'name',
            'required': ['name']
        })

    def test_model_with_discriminator_override_require(self):
        model = self.api.model('Person', {
            'name': fields.String(discriminator=True, required=False),
            'age': fields.Integer,
        })

        self.assertEqual(model.__schema__, {
            'properties': {
                'name': {'type': 'string'},
                'age': {'type': 'integer'},
            },
            'discriminator': 'name',
            'required': ['name']
        })

    def test_extend(self):
        parent = self.api.model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        child = self.api.extend('Child', parent, {
            'extra': fields.String,
        })

        self.assertEqual(child.__schema__, {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'extra': {
                    'type': 'string'
                }
            }
        })

        self.assertIn('Parent', self.api.models)
        self.assertIn('Child', self.api.models)

    def test_extend_with_multiple_parents(self):
        grand_parent = self.api.model('GrandParent', {
            'grand_parent': fields.String,
        })

        parent = self.api.model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        child = self.api.extend('Child', [grand_parent, parent], {
            'extra': fields.String,
        })

        self.assertEqual(child.__schema__, {
            'properties': {
                'grand_parent': {
                    'type': 'string'
                },
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'extra': {
                    'type': 'string'
                }
            }
        })

        self.assertIn('GrandParent', self.api.models)
        self.assertIn('Parent', self.api.models)
        self.assertIn('Child', self.api.models)

    def test_inherit(self):
        parent = self.api.model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = self.api.inherit('Child', parent, {
            'extra': fields.String,
        })

        self.assertEqual(parent.__schema__, {
            'properties': {
                'name': {'type': 'string'},
                'age': {'type': 'integer'},
            }
        })
        self.assertEqual(child.__schema__, {
            'allOf': [{
                    '$ref': '#/definitions/Parent'
                }, {
                    'properties': {
                        'extra': {'type': 'string'}
                    }
                }
            ]
        })

        self.assertIn('Parent', self.api.models)
        self.assertIn('Child', self.api.models)

    def test_inherit_inline(self):
        parent = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = self.api.inherit('Child', parent, {
            'extra': fields.String,
        })

        self.api.model('Output', {
            'child': fields.Nested(child),
            'children': fields.List(fields.Nested(child))
        })

        self.assertIn('Person', self.api.models)
        self.assertIn('Child', self.api.models)

    def test_polymorph_inherit_common_ancestor(self):
        class Child1:
            pass

        class Child2:
            pass

        parent = self.api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child1 = self.api.inherit('Child1', parent, {
            'extra1': fields.String,
        })

        child2 = self.api.inherit('Child2', parent, {
            'extra2': fields.String,
        })

        mapping = {
            Child1: child1,
            Child2: child2,
        }

        output = self.api.model('Output', {
            'child': fields.Polymorph(mapping)
        })

        # Should use the common ancestor
        self.assertEqual(output.__schema__, {
            'properties': {
                'child': {'$ref': '#/definitions/Person'},
            }
        })
Beispiel #17
0
example_address_put = app.model(
    'AddressPutModel', {'Address2': fields.String(example='Apartment 243')})

example_response = app.model(
    'AddressPostResponseModel', {
        'Country': fields.String(required=True, example='CA'),
        'Address1': fields.String(example='14 Albertson Lane'),
        'Address2': fields.String(example='Apartment 240'),
        'City': fields.String(example='Vancouver'),
        'Province': fields.String(example='BC'),
        'PostalCode': fields.Integer(example=35421),
        '_id': fields.String(example='5e6096e3b0cbe6aa74b93c19')
    })

example_response_put = app.inherit(
    'AddressPutResponseModel', example_response,
    {'Address2': fields.String(example='Apartment 243')})

# endregion


# allow the user to read address formats, and provide accessibility for frontend
@format_namespace.route('/')
class GetFormats(Resource):
    def get(self):
        return get_response(200, get_format())


# region Address API Endpoints

Beispiel #18
0
        'labels':
        fields.List(fields.String(required=False, description='Label'),
                    required=False,
                    description='Labels.')
    })

pagination = api.model(
    'A page of results', {
        'page': fields.Integer(description='Result page number.'),
        'pages': fields.Integer(description='Total number of result pages.'),
        'per_page':
        fields.Integer(description='Number of items per result page.'),
        'total': fields.Integer(description='Total number of results.'),
    })

page_of_facts = api.inherit('Page of facts', pagination,
                            {'items': fields.List(fields.Nested(fact))})

# -------------------------------------------------------------------------------------------------
# rest api - routes


@ns.route('/')
class FactsCollection(Resource):
    """
    A collection of Facts.
    """
    @api.expect(pagination_arguments)
    @api.marshal_with(page_of_facts)
    def get(self):
        """
        Returns the paged list of Facts.
Beispiel #19
0
    def test_marshal_with_honour_complex_field_mask_header(self, app, client):
        api = Api(app)

        person = api.model('Person', person_fields)
        child = api.inherit('Child', person, {'attr': fields.String})

        family = api.model(
            'Family', {
                'father': fields.Nested(person),
                'mother': fields.Nested(person),
                'children': fields.List(fields.Nested(child)),
                'free': fields.List(fields.Raw),
            })

        house = api.model(
            'House', {'family': fields.Nested(family, attribute='people')})

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(house)
            def get(self):
                return {
                    'people': {
                        'father': {
                            'name': 'John',
                            'age': 42
                        },
                        'mother': {
                            'name': 'Jane',
                            'age': 42
                        },
                        'children': [
                            {
                                'name': 'Jack',
                                'age': 5,
                                'attr': 'value-1'
                            },
                            {
                                'name': 'Julie',
                                'age': 7,
                                'attr': 'value-2'
                            },
                        ],
                        'free': [
                            {
                                'key-1': '1-1',
                                'key-2': '1-2'
                            },
                            {
                                'key-1': '2-1',
                                'key-2': '2-2'
                            },
                        ]
                    }
                }

        data = client.get_json(
            '/test/',
            headers={
                'X-Fields':
                'family{father{name},mother{age},children{name,attr},free{key-2}}'
            })
        assert data == {
            'family': {
                'father': {
                    'name': 'John'
                },
                'mother': {
                    'age': 42
                },
                'children': [{
                    'name': 'Jack',
                    'attr': 'value-1'
                }, {
                    'name': 'Julie',
                    'attr': 'value-2'
                }],
                'free': [{
                    'key-2': '1-2'
                }, {
                    'key-2': '2-2'
                }]
            }
        }
Beispiel #20
0
                       description='The unique identifier of a blog category'),
        'name':
        fields.String(required=True, description='Category name'),
        'status':
        fields.String(description='Status of the category'),
        'created_at':
        fields.DateTime(description='Creation date of the category'),
        'updated_at':
        fields.DateTime(description='Date where the category is updated'),
        'deleted_at':
        fields.DateTime(description='Date where the category is deleted')
    })

category_with_posts = api.inherit(
    'Blog category with posts',
    category,
    {
        # 'posts': fields.List(category)
    })


@ns.route('/')
class CategoryCollection(Resource):
    @api.marshal_list_with(category)
    def get(self):
        """
        Returns list of blog categories.
        """
        return CategoryRepository.get_all()

    @api.response(201, 'Category successfully created.')
    @api.expect(category)
Beispiel #21
0

# web related logic

GarageStatusModel = api.model(
    'GarageStatusModel', {
        'garage_name': fields.String(),
        'status': fields.String(),
        'error': fields.Boolean(),
        'message': fields.String(allow_null=True)
    })

NagiosGarageStatusModel = api.inherit(
    'NagiosGarageStatusModel', GarageStatusModel, {
        'return_code': fields.String(),
        'plugin_output': fields.String(),
        'status_time': fields.String(),
        'service_description': fields.String()
    })

GarageStatusResponseModel = api.model(
    'GarageStatusResponseModel', {
        'status': fields.List(fields.Nested(GarageStatusModel)),
        'type': fields.String(default='STATUS'),
        'id': fields.String()
    })


@api.route('/garage/status')
class GarageStatusResource(Resource):
    @api.marshal_with(GarageStatusResponseModel)
Beispiel #22
0
muudetavSoogikord = api.model(
    'Muudetav söögikord', {
        'liik':
        fields.String('Söögikorra liik (nt Hommikusöök, Lõunasöök, Lisaeine)'),
        'kuupäev':
        fields.String('Söögikorra toimumise kuupäev (nt "2018-02-02")'),
        'vaikimisi':
        fields.String('Kas söögikord on vaikimisi valik? (nt "True"/"False")'),
        'kirjeldus':
        fields.String(
            'Söögikorra kirjeldus (nt "6. klass saab lõunatoiduna ekskursioonile kaasa võilevad ja mahla")'
        ),
    })

soogikord = api.inherit(
    'Söögikord', muudetavSoogikord, {
        'kasutajatunnus': fields.String('Söögikorra lisaja kasutajatunnus'),
    })

avatudSoogikorrad = api.model('Registreerimiseks avatud söögikorrad', {
    'soogikorra_id': fields.Integer,
})

opilane = api.model(
    'Õpilane', {
        'isikukood': fields.String,
        'eesnimi': fields.String,
        'perekonnanimi': fields.String,
        'klass': fields.String
    })

opilaseSoogikorrad = api.model(