def create_event(self): requirement = self.api.model( 'Requirement', { 'name': fields.String(required=True, description='Event name'), 'quantity': fields.Integer(required=True, description='Name of event') }) event = self.api.model( 'Event', { 'tag': fields.String(required=False, description='Tag of event'), 'name': fields.String(required=True, description='Name of event'), 'date': fields.String(required=True, description='Date of event' ), # Cambiar el type por lo que corresponde. 'time': fields.String(required=False, description='Time of event'), 'capacity': fields.String(required=False, description='Capacity of event'), 'venue': fields.Nested(self.venueDocument.venue, required=False, description='Venue of event'), 'image': fields.String(required=False, description='Image of event'), 'description': fields.String(required=False, description='Description of event'), 'visibility': fields.String(required=True, description='Visibility of event'), 'hasAssistance': fields.Boolean(required=False, description=''), 'isOwner': fields.Boolean(required=False, description=''), 'soldOut': fields.Boolean(required=False, description=''), 'gests': fields.List(fields.String(), required=False, description='Description of event'), 'requirementMissing': fields.List(fields.Nested(requirement), required=False, description='Requirements missing'), 'requirement': fields.List(fields.Nested(requirement), required=False, description='Requirements') }) return event
def create_assistance(self): return self.api.model( 'Assistance', { 'user': fields.String(required=False, description='User'), 'event': fields.Nested(self.assistanceEvent, required=False, description='Evento'), 'requirements': fields.Nested(self.requirement, required=False, description='Requerimientos') })
def test_as_list_is_reusable(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, as_list=True) self.assertEqual(field.__schema__, { 'type': 'array', 'items': { '$ref': '#/definitions/NestedModel' } }) field = fields.Nested(nested_fields) self.assertEqual(field.__schema__, {'$ref': '#/definitions/NestedModel'})
def test_with_title(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, title='A title') self.assertEqual(field.__schema__, { '$ref': '#/definitions/NestedModel', 'title': 'A title' })
def test_with_allow_null(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, allow_null=True) self.assertFalse(field.required) self.assertTrue(field.allow_null) self.assertEqual(field.__schema__, {'$ref': '#/definitions/NestedModel'})
def test_marshal_nested_property(self): class TestObject(object): @property def fee(self): return {'blah': 'cool'} model = OrderedDict([ ('foo', fields.Raw), ('fee', fields.Nested( OrderedDict([ ('fye', fields.String), ('blah', fields.String) ]), allow_null=True)) ]) obj = TestObject() obj.foo = 'bar' obj.bat = 'baz' output = marshal([obj], model) expected = [OrderedDict([ ('foo', 'bar'), ('fee', OrderedDict([ ('fye', None), ('blah', 'cool') ])) ])] self.assertEquals(output, expected)
def test_with_description(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, description='A description') self.assertEqual(field.__schema__, { '$ref': '#/definitions/NestedModel', 'description': 'A description' })
def paginate_events(self): return self.api.model( 'EventsAsistances', { 'page': fields.Integer(required=False), 'totalPages': fields.Integer(required=False), 'events': fields.List(fields.Nested(self.event, required=False)) })
def test_with_readonly(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, readonly=True) self.assertEqual(field.__schema__, { '$ref': '#/definitions/NestedModel', 'readOnly': True })
def test_with_nested_field(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.List(fields.Nested(nested_fields)) self.assertEqual(field.__schema__, { 'type': 'array', 'items': { '$ref': '#/definitions/NestedModel' } })
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 to_doc_list_model(cls, api): model_name = '{}List'.format(cls.__name__) model = api.models.get(model_name) if model: return model meta = api.models.get('Meta') if not meta: meta = api.model('Meta', { 'total': docfields.Integer, 'previous': docfields.Url(required=False), 'next': docfields.Url(required=False), }) return api.model('{}List'.format(cls.__name__), { 'meta': docfields.Nested(meta), 'objects': docfields.Nested(cls.to_doc_model(api), as_list=True), 'include': docfields.Nested(WigoModel.to_doc_model(api), as_list=True), })
def paginate_assistances(self): return self.api.model( 'PaginateAsistances', { 'page': fields.Integer(required=False), 'totalPages': fields.Integer(required=False), 'assistances': fields.List( fields.Nested(self.assistance, required=False, description='Requerimientos')) })
def test_marshal_list_of_nesteds(self): model = OrderedDict([ ('foo', fields.Raw), ('fee', fields.List(fields.Nested({ 'fye': fields.String }))) ]) marshal_fields = OrderedDict([('foo', 'bar'), ('bat', 'baz'), ('fee', {'fye': 'fum'})]) output = marshal(marshal_fields, model) expected = OrderedDict([('foo', 'bar'), ('fee', [OrderedDict([('fye', 'fum')])])]) self.assertEquals(output, expected)
def test_marshal_nested_with_null(self): model = OrderedDict([ ('foo', fields.Raw), ('fee', fields.Nested( OrderedDict([ ('fye', fields.String), ('blah', fields.String) ]), allow_null=True)) ]) marshal_fields = OrderedDict([('foo', 'bar'), ('bat', 'baz'), ('fee', None)]) output = marshal(marshal_fields, model) expected = OrderedDict([('foo', 'bar'), ('fee', None)]) self.assertEquals(output, expected)
def test_allow_null_presents_data(self): model = OrderedDict([ ('foo', fields.Raw), ('fee', fields.Nested( OrderedDict([ ('fye', fields.String), ('blah', fields.String) ]), allow_null=True)) ]) marshal_fields = OrderedDict([('foo', 'bar'), ('bat', 'baz'), ('fee', {'blah': 'cool'})]) output = marshal(marshal_fields, model) expected = OrderedDict([ ('foo', 'bar'), ('fee', OrderedDict([('fye', None), ('blah', 'cool')])) ]) self.assertEquals(output, expected)
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' }, }})
import db_points from utilities import getRequestValues point_fields = api.model('points', { 'x': fields.Float, 'y': fields.Float, 'width': fields.Float }) image_fields = api.model( 'Image', { 'description': fields.String, 'browser': fields.String(required=False), 'deleted': fields.String(required=False), 'source_ip': fields.String(required=False), 'points': fields.List(fields.Nested(point_fields)), 'created': fields.DateTime }) class TaskImagesAPI(Resource): @api.doc(responses={404: 'Image not found'}) @api.marshal_list_with(image_fields) def get(self): """ Show all images """ images = db_images.getall() if images is None: api.abort(404)
}) rules_field = api.model( 'RulesField', { 'code': fields.String(description='rule ID', required=True), 'description': fields.String(description='description of the parking rule', required=True), 'time_max_parking': fields.Integer(description='restriction on parking time (minutes)', required=True), 'agenda': fields.Nested( agenda_view, description= '''list of days when the restriction apply (1: monday, ..., 7: sunday) containing a list of time ranges when the restriction apply''', required=True), 'permit_no': fields.String( description='city parking permit number applicable for this slot', required=True), 'special_days': fields.String(required=True), 'restrict_types': fields.List(fields.String, description='special restriction details', required=True), 'paid_hourly_rate': fields.Float( description='hourly cost for paid parking here (if applicable)')
import db_cellresults import db_cellmarks from utilities import getRequestValues mark_fields = api.model('cellmarks', { 'x': fields.Integer, 'y': fields.Integer, 'typeofmarking': fields.Float }) cell_fields = api.model('cells', { 'image_name' : fields.String(), 'browser': fields.String(required=False), 'deleted': fields.String(required=False), 'source_ip': fields.String(required=False), 'cellmarks': fields.List(fields.Nested(mark_fields)), 'created': fields.DateTime }) class TaskCellsAPI(Resource): def __init__(self): pass @api.doc(responses={404: 'Cell not found'}) @api.marshal_list_with(cell_fields) def get(self): """ Show all results """ results = db_cellresults.getall()
class VertexUpdate(Resource): vertexUpdate = api.model( 'VertexUpdate', { 'vertex': fields.String(required=True, description='Vertex Name'), 'vtype': fields.String(required=True, description='Vertex Type Name (None = 0)'), 'set_weight': fields.String(required=False, description='Edge type'), 'incr_weight': fields.Integer(required=False, description='Timestamp') }) vertexUpdateSpec = api.model( 'Update', { 'vertexUpdates': fields.List(fields.Nested(vertexUpdate), description='List of Vertex Updates', required=True), 'immediate': fields.Boolean( description= 'Instructs the API to send this batch to STINGER immediately upon receipt', required=False, default=False) }) @api.expect(vertexUpdateSpec) @api.doc( responses={ 201: 'Vertices Updated', 400: 'Bad Request', 503: 'Unable to reach STINGER' }) def post(self): exec_time = time.time() if not request.json: r = json.dumps({"error": "Invalid input"}) return Response(response=r, status=400, mimetype="application/json") # grab the lock counter_lock.acquire() try: data = request.json send_immediate = False if 'immediate' in data: if data['immediate'] == True: send_immediate = True if isinstance(data["vertexUpdates"], list): vertexUpdates = data["vertexUpdates"] print "Received batch of size", len( vertexUpdates), 'at', strftime("%Y%m%d%H%M%S", gmtime()), "" for x in vertexUpdates: try: vtx = str(x["vertex"]) vtype = str(x["vtype"]) set_weight = x["set_weight"] if 'set_weight' in x else 0 incr_weight = int( x["incr_weight"]) if 'incr_weight' in x else 0 s.add_vertex_update(vtx, vtype, set_weight, incr_weight) except Exception as e: print(traceback.format_exc()) pass # send immediately if the batch is now large current_batch_size = s.insertions_count + s.deletions_count + s.vertex_updates_count if current_batch_size > BATCH_THRESHOLD and BATCH_THRESHOLD > 0 or send_immediate: print "Sending batch of size", current_batch_size, 'at', strftime( "%Y%m%d%H%M%S", gmtime()), "" s.send_batch() except: print(traceback.format_exc()) r = json.dumps({"error": "Unable to parse object"}) return Response(response=r, status=400, mimetype="application/json") # end critical section finally: counter_lock.release() exec_time = time.time() - exec_time r = json.dumps({ "status": "success", "time": exec_time, "current_batch_size": current_batch_size }) return Response(response=r, status=201, mimetype="application/json")
class Insert(Resource): edge = api.model( 'Edge', { 'src': fields.String(required=True, description='Source vertex'), 'dest': fields.String(required=True, description='Destination vertex'), 'type': fields.String(required=False, description='Edge type'), 'weight': fields.Integer(required=False, description='Edge weight'), 'time': fields.Integer(required=False, description='Timestamp') }) edgesSpec = api.model( 'Insert', { 'edges': fields.List(fields.Nested(edge), description='List of edges', required=True), 'immediate': fields.Boolean( description= 'Instructs the API to send this batch to STINGER immediately upon receipt', required=False, default=False), 'strings': fields.Boolean( description= 'Instructs the API to interpret integer vertex names as strings rather than integer vertex IDs', required=False, default=True) }) @api.expect(edgesSpec) @api.doc(responses={ 201: 'Edge Inserted', 400: 'Bad Request', 503: 'Unable to reach STINGER' }) def post(self): setupSTINGERConnection() exec_time = time.time() if not request.json: r = json.dumps({"error": "Invalid input"}) return Response(response=r, status=400, mimetype="application/json") # grab the lock counter_lock.acquire() try: data = request.json send_immediate = False if 'immediate' not in data else data[ 'immediate'] only_strings = True if 'strings' not in data else data['strings'] if isinstance(data["edges"], list): edges = data["edges"] print "Received batch of size", len(edges), 'at', strftime( "%Y%m%d%H%M%S", gmtime()), "" for x in edges: try: if only_strings: source = str(x["src"]) destination = str(x["dest"]) else: source = x["src"] destination = x["dest"] edge_type = x["type"] if 'type' in x else 0 edge_weight = int(x["weight"]) if 'weight' in x else 0 timestamp = int(x["time"]) if 'time' in x else 0 s.add_insert(source, destination, edge_type, weight=edge_weight, ts=timestamp, insert_strings=only_strings) # print "added edge", source, destination, edge_type, timestamp except Exception as e: print(traceback.format_exc()) pass # send immediately if the batch is now large current_batch_size = s.insertions_count + s.deletions_count + s.vertex_updates_count if current_batch_size > BATCH_THRESHOLD and BATCH_THRESHOLD > 0 or send_immediate: s.send_batch() print "Sending batch of size", current_batch_size, 'at', strftime( "%Y%m%d%H%M%S", gmtime()), "" except: print(traceback.format_exc()) r = json.dumps({"error": "Unable to parse object"}) return Response(response=r, status=400, mimetype="application/json") # end critical section finally: counter_lock.release() exec_time = time.time() - exec_time r = json.dumps({ "status": "success", "time": exec_time, "current_batch_size": current_batch_size }) return Response(response=r, status=201, mimetype="application/json")
required=True, default="True", description='Set node as Master'), 'nodeData': fields.String(required=True, default="True", description='Allow node to store data'), 'shards': fields.Integer( required=True, default=5, description='Number of shards'), 'replicas': fields.Integer( required=True, default=1, description='Number of replicas'), 'networkHost': fields.String( required=True, default="0.0.0.0", description='Network host IP'), 'cacheSettings': fields.Nested(esCacheModel, description="Cache settings"), 'indexSettings': fields.Nested(esIndexSettingModel, description="Index settings") }) @agent.route('/v1/logs') class NodeLogs(Resource): def get(self): logList = os.listdir(logDir) response = jsonify({'Logs': logList}) response.status_code = 200 return response @agent.route('/v1/logs/<log>')
class ParseMaskWrapped(ParseMaskMixin, TestCase): def parse(self, value): return mask.parse('{' + value + '}') class DObject(object): '''A dead simple object built from a dictionnary (no recursion)''' def __init__(self, data): self.__dict__.update(data) person_fields = {'name': fields.String, 'age': fields.Integer} family_fields = { 'father': fields.Nested(person_fields), 'mother': fields.Nested(person_fields), 'children': fields.List(fields.Nested(person_fields)) } class ApplyMaskTest(TestCase): def test_empty(self): data = { 'integer': 42, 'string': 'a string', 'boolean': True, } result = mask.apply(data, '{}') self.assertEqual(result, {})
def test_defaults(self): nested_fields = self.api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields) self.assertFalse(field.required) self.assertEqual(field.__schema__, {'$ref': '#/definitions/NestedModel'})
'todo2': { 'task': '?????' }, 'todo3': { 'task': 'profit!' }, } todo = api.model( 'Todo', {'task': fields.String(required=True, description='The task details')}) listed_todo = api.model( 'ListedTodo', { 'id': fields.String(required=True, description='The todo ID'), 'todo': fields.Nested(todo, description='The Todo') }) def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: api.abort(404, "Todo {} doesn't exist".format(todo_id)) parser = api.parser() parser.add_argument('task', type=str, required=True, help='The task details', location='form')
from flask import g, request, jsonify from config import Configuration from server.models.event import EventMessage from server.rest import api_blueprint, WigoResource, api from server.security import user_token_required logger = logging.getLogger('wigo.web.uploads') param = api.model('UploadParam', { 'key': fields.String(required=True), 'value': fields.String(required=True) }) params = api.model('UploadParams', { 'action': fields.String(description='Form action', required=True), 'fields': fields.Nested(param, as_list=True, required=True) }) class UploadResource(WigoResource): @user_token_required def post(self): multipart_file = request.files.get('file') filename = secure_filename(multipart_file.filename) tmp_filepath = os.path.join(Configuration.UPLOAD_FOLDER, filename) multipart_file.save(tmp_filepath) cache_control = request.values.get('Cache-Control') content_type = request.values.get('Content-Type') key = request.values.get('key') logger.info('handling photo upload directly for key {key}'.format(key=key))