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, 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_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)
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'}] }}
poem_model = api.model( 'Poem', { 'paragraphs': fields.List(fields.String, example=['First paragraph.', 'Second paragraph.'], required=True), 'date_generated': fields.DateTime(dt_format='iso8601', example='2020-12-22T11:26:05.594814+00:00', required=True) }) poem_with_hash_model = api.inherit( 'Poem With Hash', poem_model, { 'hash': fields.String(example='1fe6ec3ce370e8d710a061afde3eee1d', required=True) }) time_range = reqparse.RequestParser() time_range.add_argument('from', default='2020-01-01', help='An ISO 8601 formatted date.', required=True, type=datetime.fromisoformat, location='args') time_range.add_argument('until', default='2020-02-01', help='An ISO 8601 formatted date.',
{ "id": fields.Integer( attribute="_id", description="Die ID eines Business Objects" ), "erstellungszeitpunkt": fields.String( attribute="_erstellungszeitpunkt", description="Timestamp des BO" ), }, ) nachricht = api.inherit( "Nachricht", bo, { "inhalt": fields.String(attribute="_inhalt", description="Nachrichteninhalt"), "absender_id": fields.Integer(attribute="_absender_id", description="Absender"), "konversation_id": fields.Integer( attribute="_konversation_id", description="Konversationszugehörigkeit" ), }, ) gruppenteilnahme = api.inherit( "GruppenTeilnahme", bo, { "person_id": fields.Integer( attribute="_person_id", description="Useridentifikation" ), "gruppen_id": fields.Integer( attribute="_gruppen_id", description="Gruppenidentifikation"
app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version='1.0', title='ML API Example', validate=True) ns = api.namespace('iris', description='IRIS model') iris_row = api.model( 'IrisRow', { 'sepal_length': fields.Float(required=True), 'sepal_width': fields.Float(required=True), 'petal_length': fields.Float(required=True), 'petal_width': fields.Float(required=True) }) iris_prediction = api.inherit( 'IrisPrediction', iris_row, {'prediction': fields.List(fields.Float, min_items=3, max_items=3)}) @ns.route('/') class IrisClassification(Resource): @ns.doc('obtain_prediction') @ns.expect(iris_row) @ns.marshal_with(iris_prediction, code=200) def post(self): payload = api.payload values_tuple = tuple(payload.values()) prediction = [ round(p, 5) for p in model.predict_proba([values_tuple])[0] ] payload.update({'prediction': prediction})
"""Namespaces""" electivApp = api.namespace('electivApp', description='Functions of electivApp') """Hier wird definiert, wie die Businessobjects beim Marshelling definiert werden sollen""" bo = api.model('BusinessObject', { 'id': fields.Integer(attribute='_id', description='ID des BOs'), }) automat = api.model('Automat',{ 'aktueller_zustand': fields.String(attribute='_aktueller_zustand', description='ID des aktuellen Zustands des Automaten') }) nbo = api.inherit('NamedBusinessObject', bo, { 'name': fields.String(attribute='_name', description='Name des BOs'), }) person = api.inherit('Person', nbo, { 'email': fields.String(attribute='_email', description='Email der Person'), 'google_user_id': fields.String(attribute='_google_user_id', description='Google user ID der Person'), 'rolle': fields.String(attribute='_rolle', description='Rolle der Person') }) student = api.inherit('Student', person, { 'mat_nr': fields.Integer(attribute='_mat_nr', description='Die Matrikelnummer des Studenten'), 'kuerzel': fields.String(attribute='_kuerzel', description='Kuerzel des Studenten') }) projekt = api.inherit('Projekt', nbo, automat, { 'max_teilnehmer': fields.Integer(attribute='_max_teilnehmer', description='Maximale Anzahl an teilnehmern'),
fields.String(required=True, description='The last name of the Customer'), 'email': fields.String(required=True, description='The email of the Customer'), 'address': fields.String(required=True, description='The address of the Customer'), 'active': fields.Boolean(required=True, description='Is the Customer avaialble for purchase?') }) customer_model = api.inherit( 'CustomerModel', create_model, { 'id': fields.String( readOnly=True, description='The unique id assigned internally by service'), }) # query string arguments customer_args = reqparse.RequestParser() customer_args.add_argument('first_name', type=str, required=False, help='List Customers by first name') customer_args.add_argument('last_name', type=str, required=False, help='List Customers by last name') customer_args.add_argument('email',
description='Erstellungszeitpunkt des Objekts') }) nbo = api.model( 'NamedBusinessObject', { 'name': fields.String(attribute='_name', description='Der Name eines Named Business Object'), }) user = api.inherit( 'User', bo, { 'name': fields.String(attribute='_name', description='Name eines Benutzers'), 'email': fields.String(attribute='_email', description='E-Mail-Adresse eines Benutzers'), 'user_id': fields.String(attribute='_user_id', description='Google User ID eines Benutzers') }) module = api.inherit('Module', bo, nbo, { 'edv_nr': fields.String(attribute='_edv_nr', description='EDV_Nr des Moduls') }) participation = api.inherit( 'Participation', bo, { 'project': fields.Integer(attribute='_project',
von Namespace könnte etwa sein, unterschiedliche API-Version voneinander zu trennen, um etwa Abwärtskompatibilität (vgl. Lehrveranstaltungen zu Software Engineering) zu gewährleisten. Dies ließe sich z.B. umsetzen durch /bank/v1, /bank/v2 usw.""" banking = api.namespace('bank', description='Funktionen des BankBeispiels') """Nachfolgend werden analog zu unseren BusinessObject-Klassen transferierbare Strukturen angelegt. BusinessObject dient als Basisklasse, auf der die weiteren Strukturen Customer, Account und Transaction aufsetzen.""" bo = api.model('BusinessObject', { 'id': fields.Integer(attribute='_id', description='Der Unique Identifier eines Business Object'), }) """Users, Customers, Accounts & Transactions sind BusinessObjects...""" user = api.inherit('User', bo, { 'name': fields.String(attribute='_name', description='Name eines Benutzers'), 'email': fields.String(attribute='_email', description='E-Mail-Adresse eines Benutzers'), 'user_id': fields.String(attribute='_user_id', description='Google User ID eines Benutzers') }) customer = api.inherit('Customer', bo, { 'first_name': fields.String(attribute='_first_name', description='Vorname eines Kunden'), 'last_name': fields.String(attribute='_last_name', description='Nachname eines Kunden') }) account = api.inherit('Account', bo, { 'owner': fields.Integer(attribute='_owner', description='Unique Id des Kontoinhabers') }) transaction = api.inherit('Transaction', bo, { 'source_account': fields.Integer(attribute='_source_account', description='Unique Id des Quellkontos'), 'target_account': fields.Integer(attribute='_target_account', description='Unique Id des Zielkontos'),
zu den methoden (api.model/api.inherit) findet man mehr auf der Flask Seite unter Response marshalling https://flask-restplus.readthedocs.io/en/stable/marshalling.html?highlight=nested#nested-field """ bo = api.model('BusinessObject', { 'name': fields.String(attribute='_name', description='Name eines Objekts'), 'id': fields.Integer(attribute='_id', description='Der Unique Identifier eines Business Object'), 'creation_date' : fields.Integer(attribute='_creation_date', description='Erstellungsdatum des BOs, wird durch Unix Time Stamp ermittlet') }) """mit attribute='' wird gerenamed""" group = api.inherit('Group', bo, { 'owner_id': fields.Integer(attribute='_owner', description='Unique Id des Kontoinhabers'), 'members': fields.Array(attribute='_members', description='Eine liste aller Gruppenmitglieder'), 'articles' : fields.Array(attribute='_articles', description='Liste aller Artikeln'), 'shoppingslists' : fields.Array(attribute='_shoppinglist', description='Liste aller listen der Gruppe'), 'standardarticles' : fields.Array(attribute='_standardarticles', description='Liste aller standardartikeln der Gruppe'), }) person = api.inherit('Person', bo, { 'email': fields.String(attribute='_email', description='E-Mail-Adresse eines Benutzers'), 'groups': fields.Array(attribute='_groups', description='Eine liste aller Gruppen an der die Person beteiligt ist '), }) """Datentyp von Gruppe?""" shoppingList = api.inherit('ShoppingList', bo, { 'group': fields.String(attribute='_group', description='zu welcher groupe diese Liste gehört'), 'list_entries': fields.Array(attribute='_list_entries',
) wm_text_model = api.model( 'WMText', {'text': fields.String(example='Rainfall causes floods.', description='Text to process')}) jsonld_model = api.model( 'jsonld', {'jsonld': fields.String(example='{}', description='JSON-LD reader output')}) eidos_text_model = api.inherit('EidosText', wm_text_model, { 'webservice': fields.String(description='URL for Eidos webservice'), 'grounding_ns': fields.List( fields.String, example=['WM'], required=False, description='A list of name spaces for which INDRA should represent groundings'), 'extract_filter': fields.List( fields.String, example=['influence'], required=False, description='A list of relation types to extract'), 'grounding_mode': fields.String(example='flat', required=False) }) eidos_jsonld_model = api.inherit('EidosJson', jsonld_model, { 'grounding_ns': fields.List( fields.String, example=['WM'], required=False, description='A list of name spaces for which INDRA should ' 'represent groundings'), 'extract_filter': fields.List( fields.String, example=['influence'], required=False, description='A list of relation types to extract'), 'grounding_mode': fields.String(example='flat', required=False, description='flat or compositional')
'sex': fields.Integer(required=True), 'cp': fields.Integer(required=True), 'trestbps': fields.Integer(required=True), 'chol': fields.Integer(required=True), 'fbs': fields.Integer(required=True), 'restecg': fields.Integer(required=True), 'thalach': fields.Integer(required=True), 'exang': fields.Integer(required=True), 'oldpeak': fields.Integer(required=True), 'slope': fields.Integer(required=True), 'ca': fields.Integer(required=True), 'thal': fields.Integer(required=True) }) heart_prediction = api.inherit('HeartPrediction', heart_row, { 'prediction': fields.List(fields.Float, min_items=2, max_items=2), 'prediction_class': fields.Integer }) @ns.route('/') class HeartClassification(Resource): @ns.doc('obtain_prediction') @ns.expect(heart_row) @ns.marshal_with(heart_prediction, code=200) def post(self): payload = api.payload values_tuple = tuple(payload.values()) prediction = [round(p, 5) for p in model.predict_proba([values_tuple])[0]] predicted_class = np.argmax(prediction) payload.update({'prediction': prediction}) payload.update({'prediction_class': predicted_class}) return payload
'corpus_id': fields.String(example='corpus1', required=False) } ) wm_text_model = api.model( 'WMText', {'text': fields.String(example='Rainfall causes floods.')}) jsonld_model = api.model( 'jsonld', {'jsonld': fields.String(example='{}')}) eidos_text_model = api.inherit('EidosText', wm_text_model, { 'webservice': fields.String, 'grounding_ns': fields.List(fields.String(example=['WM']), required=False), 'extract_filter': fields.List(fields.String(example=['Influence']), required=False), 'grounding_mode': fields.String(example='flat', required=False) }) eidos_jsonld_model = api.inherit('EidosJson', jsonld_model, { 'grounding_ns': fields.List(fields.String(example=['WM']), required=False), 'extract_filter': fields.List(fields.String(example=['Influence']), required=False), 'grounding_mode': fields.String(example='flat', required=False) }) sofia_json_model = api.model( 'json', {'json': fields.String(example='{}'), 'extract_filter': fields.List(fields.String(example=['Influence']),
app = Flask(__name__) CORS(app, resources=r"/shopping/*") api = Api(app, version='1.0', title='ShoppingList API', description='Das ist unserer API für die Shoppinglist.') shopping = api.namespace('shopping', description='Funktionen der Shoppinglist') bo = api.model('BusinessObject', { 'id': fields.Integer(attribute='_id', description='Der Unique Identifier eines Business Object'), }) namedBO = api.inherit('namedBO', bo, { 'name': fields.String(attribute='_name', description='Name des namedBO'), 'erstellungs_zeitpunkt': fields.String(attribute='_erstellungs_zeitpunkt', description='Erstellungszeitpunkt'), }) artikel = api.inherit('Artikel', namedBO, { 'einheit': fields.String(attribute='_einheit', description='Name eines Artikels'), 'standardartikel': fields.Boolean(attribute='_standardartikel', description='Standardartikel'), 'benutzer_id': fields.Integer(attribute='_benutzer_id', description='BenutzerID'), }) einzelhaendler = api.inherit('Einzelhandler', namedBO, bo) benutzer = api.inherit('Benutzer', namedBO, { 'email': fields.String(attribute='_email', description='Email des Benutzers'), 'google_id': fields.String(attribute='_google_id', description='Google ID des Benutzers') })
attribute='_id', description='Der Unique Identifier eines Business Object'), 'create_time': fields.Date(attribute='_create_time', description='Erstellungszeitpunkt eines Business Objects') }) """Participation, Validation und NamedBusinessObject sind BusinessObjects...""" participation = api.inherit( 'Participation', bo, { 'module_id': fields.Integer(attribute='_module_id', description='Die ID des zugehörigen Moduls'), 'project_id': fields.Integer(attribute='_project_id', description='Die ID des zugehörigen Projektes'), 'student_id': fields.Integer(attribute='_student_id', description='Die ID des zugehörigen Studenten'), 'validation_id': fields.Integer(attribute='_validation_id', description='Die ID der zugehörigen Bewertung') }) validation = api.inherit( 'Validation', bo, { 'grade': fields.String(attribute='_grade', description='Bewertung eines Projektes') })
fields.DateTime(attribute='_creation_date', description='Erstellungsdatum des BOs, wird ' 'durch Unix Time Stamp ermittlet', dt_format="iso8601"), 'lastUpdated': fields.DateTime(attribute='_last_updated', description='Änderungsdatum des BOs, wird durch' 'Unix Time Stamp ermittlet', dt_format="iso8601") }) user = api.inherit( 'User', bo, { 'email': fields.String(attribute='_email', description='E-Mail-Adresse eines Benutzers'), 'googleId': fields.String(attribute='_google_id', description='google id eines Benutzers'), }) group = api.inherit( 'Group', bo, { 'owner': fields.Integer(attribute='_owner', description='Unique Id des Gruppeninhabers'), }) shopping_list = api.inherit( 'ShoppingList', bo, { 'groupId':
}) nbo = api.model('NamedBusinessObject', { 'name': fields.String(attribute='_name', description='Name eines BusinessObjects bzw. NamedBusinessObjects') }) automat = api.model('Automat', { 'current_state': fields.String(attribute='_current_state', description='Aktueller Zustand') }) """Participation, Grading, Module, Project, ProjectType, Semester, Person & Student sind BusinessObjects""" participation = api.inherit('Participation', bo, { "student_id": fields.Integer(attribute='_student_id'), 'project_id': fields.Integer(attribute='_project_id') }) grading = api.inherit('Grading', bo, { 'grade': fields.Float(attribute='_grade', description='Note zur Bewertung einer Projektteilnahme'), 'participation_id': fields.Integer(attribute='participation_id') }) module = api.inherit('Module', bo, nbo, { 'edv_number': fields.String(attribute='_edv_number', description='EDV-Nummer eines Moduls') }) project = api.inherit('Project', bo, nbo, automat, { 'capacity': fields.Integer(attribute='_capacity',
""" Transferable structure: """ bo = api.model( 'BusinessObject', { 'id': fields.Integer(attribute='_id', description="unique bo id"), }) """ Business Objects: Group, ListEntry, user, retailer, report, article, shoppinglist and favourite articles """ group = api.inherit( 'Group', bo, { 'name': fields.String(attribute='name', description="A groups name"), 'description': fields.String(attribute='description', description="A groups description"), 'creationdate': fields.DateTime(attribute='creationdate', description="The creationdate of group") }) user = api.inherit( 'User', bo, { 'name': fields.String(attribute='_name', description="An users name"), 'email': fields.String(attribute='_email', description="An users email"), 'firebase_id': fields.String(attribute='_firebase_id', description="An users firebaseid"),
"""Namespaces""" volleyTrain = api.namespace('volleyTrain', description='Functions of volleyTrain') """Hier wird definiert, wie die Businessobjects beim Marshelling definiert werden sollen""" bo = api.model( 'BusinessObject', { 'id': fields.Integer(attribute='_id', description='ID des BOs'), 'creation_date': fields.DateTime(attribute='_creation_date', description='Erstellungszeitpunkt') }) nbo = api.inherit( 'NamedBusinessObject', bo, { 'name': fields.String(attribute='_name', description='Name des BOs'), }) user = api.inherit( 'user', nbo, { 'surname': fields.String(attribute='_surname', description='Surname of user'), 'email': fields.String(attribute='_email', description='Email der Person'), 'googleUserId': fields.String(attribute='_googleUserId', description='Google user ID der Person'), }) player = api.inherit( 'nbo', nbo, {
res = {'statements': stmts} else: res = {'statements': []} return res # Create Resources in Preassembly Namespace # Manually add preassembly resources not based on assembly corpus functions pipeline_model = api.inherit( 'Pipeline', stmts_model, { 'pipeline': fields.List(fields.Nested(dict_model), example=[{ 'function': 'filter_grounded_only' }, { 'function': 'run_preassembly', 'kwargs': { 'return_toplevel': False } }]) }) # There's an extra blank line between parameters here and in all the following # docstrings for better visualization in Swagger @preassembly_ns.expect(pipeline_model) @preassembly_ns.route('/pipeline') class RunPipeline(Resource): @api.doc(False) def options(self):
'is_site_wide': fields.Boolean( required=False, description='Is the promotion site wide?' ), 'products': fields.List( cls_or_instance=fields.Integer, required=False, description='List of products associated with the promotion.', ), }, ) promotion_model = api.inherit( 'PromotionModel', create_model, { 'id': fields.Integer( readOnly=True, description='The unique id assigned internally by service' ), }, ) ###################################################################### # Error Handlers ###################################################################### @api.errorhandler(DataValidationError) def request_validation_error(error): """ Handles Value Errors from bad data """ app.logger.error(str(error)) return { 'status_code': status.HTTP_400_BAD_REQUEST, 'error': 'Bad Request',