def test_with_scoped_attribute_on_dict_or_obj(self): class Test(object): def __init__(self, data): self.data = data class Nested(object): def __init__(self, value): self.value = value nesteds = [Nested(i) for i in ['a', 'b', 'c']] test_obj = Test(nesteds) test_dict = {'data': [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}]} field = fields.List(fields.String(attribute='value'), attribute='data') assert ['a' == 'b', 'c'], field.output('whatever', test_obj) assert ['a' == 'b', 'c'], field.output('whatever', test_dict)
def unpack_nested(val, api, model_name: str = None, operation: str = "dump"): if val.nested == "self": return unpack_nested_self(val, api, model_name, operation) model_name = get_default_model_name(val.nested) if val.many: return fr.List( fr.Nested( map_type(val.nested, api, model_name, operation), **_ma_field_to_fr_field(val) ) ) return fr.Nested( map_type(val.nested, api, model_name, operation), **_ma_field_to_fr_field(val) )
def test_marshal_wildcard_list(self): wild = fields.Wildcard(fields.List(fields.String)) wildcard_fields = OrderedDict([("*", wild)]) model = OrderedDict([("preview", fields.Nested(wildcard_fields))]) sub_dict = OrderedDict( [("1:1", [1, 2, 3]), ("16:9", [4, 5, 6]), ("9:16", [7, 8, 9])] ) marshal_dict = OrderedDict([("preview", sub_dict)]) output = marshal(marshal_dict, model) assert output == { "preview": { "9:16": ["7", "8", "9"], "16:9": ["4", "5", "6"], "1:1": ["1", "2", "3"], } }
def test_list_fields_with_raw(self): family_fields = { 'members': fields.List(fields.Raw) } result = mask.apply(family_fields, 'members{name}') data = {'members': [ {'name': 'John', 'age': 42}, {'name': 'Jane', 'age': 42}, ]} expected = {'members': [{'name': 'John'}, {'name': 'Jane'}]} assert_data(marshal(data, result), expected) # Should leave th original mask untouched assert_data(marshal(data, family_fields), data)
def test_with_scoped_attribute_on_dict_or_obj(self): class Test(object): def __init__(self, data): self.data = data class Nested(object): def __init__(self, value): self.value = value nesteds = [Nested(i) for i in ["a", "b", "c"]] test_obj = Test(nesteds) test_dict = {"data": [{"value": "a"}, {"value": "b"}, {"value": "c"}]} field = fields.List(fields.String(attribute="value"), attribute="data") assert ["a" == "b", "c"], field.output("whatever", test_obj) assert ["a" == "b", "c"], field.output("whatever", test_dict)
class PatientsLists(Resource): model = namespace.model( 'PatientsData', { 'patients': fields.List(required=True, cls_or_instance=fields.Nested(patient_out)), }) @namespace.response(code=200, model=model, description='') @namespace.response( code=500, model=failed_response, description='Unexpected error, see contents for details.') def get(self): patients = PatientRepository.get_all_active() result = [] for pa in patients: result.append(_patient_model_to_dto(pa)) return result @namespace.doc(body=patient_in_post_put) @namespace.response(code=200, model=patient_out, description='') @namespace.response(code=400, model=failed_response, description='') @namespace.response(code=401, model=failed_response, description='') @namespace.response(code=500, model=failed_response, description='') def post(self): post_data = request.get_json() pa = PatientModel(first_name=post_data['first_name'], last_name=post_data['last_name'], date_of_birth=_parse_datetime( post_data['date_of_birth']), height=float(post_data['height']), weight=float(post_data['weight']), sex=post_data['sex'], active=True, heparin=False, insulin=False, target_aptt_low=None, target_aptt_high=None, solution_heparin_iu=25000, solution_ml=500, tddi=None, target_glycemia=None, other_params={}) return _update_patient(pa, post_data, True)
def test_list_fields_with_simple_field(self): family_fields = { 'name': fields.String, 'members': fields.List(fields.String) } result = mask.apply(family_fields, 'members') assert set(result.keys()) == set(['members']) assert isinstance(result['members'], fields.List) assert isinstance(result['members'].container, fields.String) data = {'name': 'Doe', 'members': ['John', 'Jane']} expected = {'members': ['John', 'Jane']} assert_data(marshal(data, result), expected) # Should leave th original mask untouched assert_data(marshal(data, family_fields), data)
def unpack_nested_self(val, api, model_name: str = None, operation: str = "dump"): model_name = model_name or get_default_model_name(val.schema) fields = { k: map_type(v, api, model_name, operation) for k, v in (vars(val.schema).get("fields").items()) if type(v) in type_map and _check_load_dump_only(v, operation) } if val.many: return fr.List( fr.Nested(api.model(f"{model_name}-child", fields), **_ma_field_to_fr_field(val))) else: return fr.Nested(api.model(f"{model_name}-child", fields), **_ma_field_to_fr_field(val))
def getResultModel(self, recordModel): paginationModel = self.flastRestPlusAPIObject.model( 'paginationList', { 'offset': fields.Integer(default='0', description='Number to start from'), 'pagesize': fields.Integer(default='', description='Results per page'), 'total': fields.Integer(default='0', description='Total number of records in output') }) return self.flastRestPlusAPIObject.model( 'resultList', { 'pagination': fields.Nested(paginationModel), 'result': fields.List(fields.Nested(recordModel)), })
class HySDSIOTypes(Resource): """Get list of registered hysds-io and return as JSON.""" resp_model_job_types = hysds_io_ns.model('HySDS IO List Response(JSON)', { 'success': fields.Boolean(required=True, description="Boolean, whether the API was successful"), 'message': fields.String(required=True, description="message describing success or failure"), 'result': fields.List(fields.String, required=True, description="list of hysds-io types") }) @hysds_io_ns.marshal_with(resp_model_job_types) def get(self): hysds_ios = mozart_es.query(index=HYSDS_IOS_INDEX, _source=False) ids = [hysds_io['_id'] for hysds_io in hysds_ios] return { 'success': True, 'message': "", 'result': ids }
class HDDSMARTPredictionDto: api = Namespace('HDDSMARTPrediction', description='HDDSMARTPrediction related operations') smart_prediction = api.model( 'SMARTPrediction', { 'track_dev_id': fields.String(30, description='tracked device id', example="0"), 'timestamp': fields.String(30, description='Prediction Timestamp', example="2019-12-01 14:20:30"), 'model': fields.String(required=True, description='HDD model', example="XYZ"), 'serial_number': fields.String(required=True, description='HDD serial number', example="HD00"), 'capacity_bytes': fields.Integer(example=1000000000), 'failure': fields.Integer, 'prediction': fields.Float } ) prediction_list_example = {'prediction_list': [ { "track_dev_id": "0", "timestamp": "2019-12-01 14:20:30", "model": "XYZ", "serial_number": "HD00", "capacity_bytes": 1000000000, "failure": 0, "prediction": 0 }, { "track_dev_id": "1", "timestamp": "2019-12-01 14:20:40", "model": "UVT", "serial_number": "00DH", "capacity_bytes": 1000000001, "failure": 1, "prediction": 1 } ] } smart_prediction_list = api.model( 'SMARTPredictionList', { 'prediction_list': fields.List(fields.Nested(smart_prediction)) } )
def getCreateTicketTypeModel(appObj): return appObj.flastRestPlusAPIObject.model( 'CreateTicketType', { 'tenantName': fields.String(default='DEFAULT', description='Tenant name for this ticket type'), 'ticketTypeName': fields.String(default='DEFAULT', description='Name displayed on admin screent'), 'description': fields.String(default='DEFAULT', description='Description of ticket type'), 'enabled': fields.Boolean( default=False, description='Can the ticket type currently be used'), 'welcomeMessage': fields.Nested(getCreateTicketTypeModel_welcomeMessage(appObj), skip_none=True), 'allowUserCreation': fields.Boolean( default=False, description= 'Allow unknown logins to create new users when using this ticket.' ), 'issueDuration': fields.Integer( default='DEFAULT', description='Hours to issue ticket for on creation'), 'roles': fields.List( fields.String( default='DEFAULT', description='List of roles this tickert type will assign') ), 'postUseURL': fields.String( default='DEFAULT', description='URL to send user to after ticket is used'), 'postInvalidURL': fields.String( default='DEFAULT', description= 'URL to send user to after invalid or request validaiton') })
class TelegramDTO: api = Namespace('telegram', description='telegram related operations') channel = api.model('TelegramMessageChannel', { 'username': fields.String, 'title': fields.String }) message = api.model( 'TelegramMessage', { 'id': fields.Integer, 'date': fields.DateTime, 'text': fields.String, 'views': fields.Integer, 'link': fields.Url, 'channel': fields.Nested(channel), 'sentiment': fields.String }) response = api.model('TelegramResponse', {'messages': fields.List(fields.Nested(message))})
def test_model_as_dict_with_list(self): model = Model( "Person", { "name": fields.String, "age": fields.Integer, "tags": fields.List(fields.String), }, ) assert model.__schema__ == { "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "tags": {"type": "array", "items": {"type": "string"}}, }, "type": "object", }
def test_model_as_nested_dict_with_list(self): address = Model('Address', { 'road': fields.String, }) person = Model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'addresses': fields.List(fields.Nested(address)) }) assert person.__schema__ == { # 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'addresses': { 'type': 'array', 'items': { '$ref': '#/definitions/Address', } } }, 'type': 'object' } assert address.__schema__ == { 'properties': { 'road': { 'type': 'string' }, }, 'type': 'object' }
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)
class CapituloDTO: api = Namespace('capitulo', description='Operaciones de los capitulos') capitulo = api.model( 'capitulo', { 'id': fields.Integer(), 'numero': fields.Integer(required=True, description='numero del capitulo'), 'proyecto_id': fields.Integer(required=True, description='id del proyecto'), 'descripcion': fields.String(required=True, description='descripcion del capitulo'), 'subtotal': fields.Float(required=True, description='subtotal del capitulo'), 'items': fields.List(fields.Nested(ItemDTO.item), description='items del capitulo'), })
class SavedInfoDto: api = Namespace('saved-info', description='Operations for saving in-game data') location = api.model(name='location', model={ 'x': fields.Integer(), 'y': fields.Integer() }) saved_info = api.model(name='saved-info', model={ 'guest': fields.Boolean(required=False, readonly=True, description='Whether this player is guest or signed'), 'savedId': fields.Integer(required=False, readonly=True, description='Unique saved-info identifier'), 'guestPassword': fields.String(required=False, readonly=True, description='One-time password needed when loading the info'), 'channelId': fields.Integer(description='Identifier for channel that game belongs'), 'playerName': fields.String(description='The player\'s name'), 'score': fields.Integer(description='The point that player gained till saves the game info'), 'location': fields.Nested(model=location, description='The location player saved this data and quit the gmae.'), 'items': fields.List(fields.String(), description='List of items the player has'), 'dateSaved': fields.DateTime(required=False, readonly=True, description='The date player saved this game') })
def test_list_fields_with_nested(self): family_fields = { 'members': fields.List(fields.Nested(person_fields)) } result = mask.apply(family_fields, 'members{name}') assert set(result.keys()) == set(['members']) assert isinstance(result['members'], fields.List) assert isinstance(result['members'].container, fields.Nested) assert set(result['members'].container.nested.keys()) == set(['name']) data = {'members': [ {'name': 'John', 'age': 42}, {'name': 'Jane', 'age': 42}, ]} expected = {'members': [{'name': 'John'}, {'name': 'Jane'}]} assert_data(marshal(data, result), expected) # Should leave th original mask untouched assert_data(marshal(data, family_fields), data)
class PlaylistDto: api = Namespace("playlists", description="Playlist related operations.") playlist_obj = api.model( "Playlist object", { "id": fields.Integer, "name": fields.String, "tracks": fields.List(fields.Nested(TrackDto.track_obj)) }, ) data_resp = api.model( "Playlist Data Response", { "status": fields.Boolean, "message": fields.String, "track": fields.Nested(playlist_obj), }, )
class RequestDto: api = Namespace('request', description='request related operations') request = api.model('request_details', { 'request_id': fields.String(required=True, description='The request id'), 'status': fields.String(required=True, description='approved/review'), 'review_msg': fields.String(required=False, description='In case of review req'), }) timeline_item = api.model('timeline_item', { 'actor': fields.String(description='The actor of the item'), 'datetime': fields.DateTime(description='Time when event occurred'), 'message': fields.String(description='Description of the event/feedback') }) history = api.model('request_history', { 'current_status': fields.String(required=False, description='The current status of the request'), 'timeline': fields.List(fields.Nested(timeline_item), description='History of the request', required=False), 'status': fields.String(required=False, description='status of request'), 'message': fields.String(request=False, description='error message if failed') })
class nerSentences(Resource): sentences_input = api.model('Sentences_Input', { 'sentences': fields.List(fields.String), }) @api.expect(sentences_input) def post(self, language): sentences = request.json["sentences"] if language in SupportedLanguages.getSupportedLanguages(): if sentences is not None and len(sentences) > 0: task = celery_app.send_task( "celery_tasks.processNERRequest", args=[language, sentences, "sentences"]) return createIdResponse(task.id, language) return createErrorResponse("Empty text", 400) return createErrorResponse("Unsupported language", 400) def options(self, language): return createOptionsResponse(self)
def init_models(cls, api: Api): cls.label = api.model( 'Label', dict( label_id=fields.String(readOnly=True), name=fields.String(readOnly=True), uri=fields.Url('labels_label'), )) cls.box = api.model( 'Box', dict(top=fields.Float(), left=fields.Float(), bottom=fields.Float(), right=fields.Float())) cls.label_assignment = api.model( 'LabelAssignment', dict( label=fields.Nested(cls.label), label_assignment_id=fields.String(readOnly=True), box=fields.Nested(cls.box, allow_null=True), confidence=fields.Float(), origin=fields.String(), uri=fields.Url('labels_assignment'), )) cls.image = api.model( 'Image', dict( image_id=fields.String(readOnly=True, description='Image ID'), file=fields.String(readOnly=True, description='Image file name'), label_assignments=fields.List(fields.Nested( cls.label_assignment), readOnly=True), url=fields.String(readOnly=True, description='Image file url'), thumbnail_url=fields.String(readOnly=True, description='Thumbnail file url'), uri=fields.Url('images_image'), ))
def get_restx_model() -> Model: return Model( "User Model", { "id": restxFields.Integer(), "time_created": restxFields.DateTime(), "time_updated": restxFields.DateTime(), "username": restxFields.String(), "email": restxFields.String(), "active": restxFields.Boolean(), "first_name": restxFields.String(), "last_name": restxFields.String(), "birthday": restxFields.Date(), "height_inches": restxFields.Float(), "weight_lbs": restxFields.Float(), "gender": restxFields.String(), "household": restxFields.Raw(), "household_id": restxFields.Integer(), "roles": restxFields.List(restxFields.Raw()), }, )
class TracsactionRetrieve(Resource): transaction_wrapper = {"data": fields.List(fields.Nested(trans_list))} transaction_response_http = api.inherit("Money Transfer HTTP", httpResponseBase, transaction_wrapper) @jwt_required @api.marshal_with(httpResponseBase_response) def get(self): uuid = get_jwt_identity()['uuid'] trans = getUserTracsactionList(uuid) return HttpResponse( data={[{ "trans": trans.get('data'), "total_transfer_in_success": trans.get('total_transfer_in_success'), "total_transfer_out_success": trans.get('total_transfer_out_success') }]}), 200
class DatasetDto: api = Namespace('dataset', description='Dataset related operations') dataset_list = api.model('dataset_list', { 'dataset_names': fields.List(fields.String(description='Dataset names')) }) schema = api.model( 'dataset_schema', { 'dataset_schema': fields.String(required=True, description='Dataset Schema'), }) table = api.model( 'create_table', { 'keyspace': fields.String(required=True, description='Keyspace Name'), 'create_stmt': fields.String(required=True, description='CQL Create Statement'), })
class VendorDto: api = Namespace('vendor', description='vendor related operations') location = api.model('location', { 'lat': fields.Float(required=True), 'lng': fields.Float(required=True), }) schedule = api.model('schedule', { 'start': fields.DateTime(required=True), 'end': fields.DateTime(required=True), }) vendor = api.model('vendor', { 'displayed_name': fields.String(description='vendor displayed name'), 'username': fields.String(required=True, description='vendor username'), 'location': fields.Nested(location, description='vendor location'), 'schedule': fields.Nested(schedule, description='vendor schedule'), 'tags': fields.List(fields.String), 'is_open': fields.Boolean(readonly=True, description='is vendor open'), }) vendor_detail = api.inherit('vendor_detail', vendor, { 'description': fields.String(description='vendor description'), })
class PositionsDto: api = Namespace('positions', description='data related operations') positions_model = api.model( 'positions', { 'latitudeE7': fields.Integer(required=True, description='Latitude coordinate'), 'longitudeE7': fields.Integer(required=True, description='Longitude coordinate'), 'altitude': fields.Integer(required=False, description='Altitude in meters'), 'verticalAccuracy': fields.Integer(required=False, description='Vertical accuracy'), 'accuracy': fields.Integer(required=True, description='Accuracy in meters'), 'timestampMs': fields.Integer(required=True, description='Timestamp in ms'), }) response_model = api.model( "data", { 'positions': fields.List(fields.Nested(positions_model)), })
class OverlapsByIdTypeDataset(Resource): """Get all dataset results that overlap temporally and spatially with dataset ID of a certain type and dataset.""" model = api.model('OverlapsByIdTypeDataset', { 'success': fields.Boolean(description="success flag"), 'message': fields.String(description="message"), 'results': fields.List(fields.Raw), 'total': fields.Integer(description="total"), 'count': fields.Integer(description="count"), 'page_size': fields.Integer(description="page size"), 'offset': fields.Integer(description="starting offset (0 index)"), }) decorators = [limiter.limit("10/second")] @token_required @api.marshal_with(model) @api.doc(security='apikey') def get(self, dataset_id, type_name, dataset_name, ret_fields): terms = { 'dataset_type.keyword': type_name, 'dataset.keyword': dataset_name, } try: index = current_app.config["ES_INDEX"] page_size, offset = get_page_size_and_offset(request) total, docs = current_app.es_util.overlaps(index, dataset_id, terms, ret_fields, offset, page_size) return { 'success': True, 'total': total, 'count': len(docs), 'page_size': page_size, 'offset': offset, 'results': docs } except Exception as e: current_app.logger.error(traceback.format_exc()) return { 'success': False, 'message': str(e), }, 500
def test_with_nested_field(self, api): nested_fields = api.model("NestedModel", {"name": fields.String}) field = fields.List(fields.Nested(nested_fields)) assert field.__schema__ == { "type": "array", "items": { "$ref": "#/definitions/NestedModel" }, } data = [{ "name": "John Doe", "age": 42 }, { "name": "Jane Doe", "age": 66 }] expected = [ OrderedDict([("name", "John Doe")]), OrderedDict([("name", "Jane Doe")]), ] self.assert_field(field, data, expected)