def test_attribute_mapped_no_pattern(self): o = fields.AttributeMapped( fields.Object({"foo": fields.Integer()}), mapping_attribute="key" ) self.assertEqual( [{'foo': 1, 'key': 'A3'}, {'foo': 1, 'key': 'B12'}], sorted( o.convert({"A3": {"foo": 1}, "B12": {"foo": 1}}), key=itemgetter("key") ), ) self.assertEqual( {"A3": {"foo": 1}, "B12": {"foo": 2}}, o.format([{'foo': 1, 'key': 'A3'}, {'foo': 2, 'key': 'B12'}]), ) self.assertEqual( { "type": "object", "additionalProperties": { "additionalProperties": False, "properties": {"foo": {"type": "integer"}}, "type": "object", }, }, o.response, )
class Schema: id = fields.Integer(io='r') due_date = fields.DateString() category = ToOneIntegerField(CategoryResource) user = ToOneIntegerField(UserResource) bids = ToManyIntegerField('bids') distance_in_meters = DistanceField(io='r', attribute='location')
class FooResource(Resource): @Route.GET(lambda r: '/<{}:id>'.format(r.meta.id_converter), rel="self") def read(self, id): return {"id": id} read.response_schema = fields.Object({"id": fields.Integer()}) class Meta: name = 'foo' id_converter = 'int'
def agroup_summary(self, id: fields.String(), year: fields.Integer()) -> fields.String(): agroup_id = id report_year = year # current_year = datetime.datetime.now().year gs = [g.id for g in models.Group.query.filter( models.Group._deleted_at == None, models.Group.associate_group_id == agroup_id, models.Group.created_at <= report_year).all()] response = { # 'total_of_gr': len(gs), 'total_of_gr': len(gs), 'total_of_farmer': 0, 'total_of_male': 0, 'total_of_female': 0, 'total_of_cert': 0, 'total_of_area': 0, 'total_of_approved_area': 0 } start_time = datetime.datetime(report_year, 1, 1) \ .strftime('%Y-%m-%d') end_time = datetime.datetime(report_year, 12, 30) \ .strftime('%Y-%m-%d') for g in gs: cs = models.Certificate.query.filter( models.Certificate.owner_group_id == g, models.Certificate.certificate_expiry_date >= start_time, models.Certificate.certificate_expiry_date <= end_time)\ .all() for cert in cs: if cert.re_verify_status == \ c.CertificateReVerifyStatusType.adding or \ cert.re_verify_status == \ c.CertificateReVerifyStatusType.converting: response['total_of_area'] += cert.group_area if cert.re_verify_status == \ c.CertificateReVerifyStatusType.adding and \ cert.status == c.CertificateStatusType.approved: response['total_of_approved_area'] += cert.group_area response['total_of_cert'] += 1 fs = models.Farmer.query.filter( models.Farmer.group_id == g, models.Farmer._deleted_at == None, models.Farmer.created_at <= report_year).all() males = models.Farmer.query.filter( models.Farmer.group_id == g, models.Farmer._deleted_at == None, models.Farmer.gender == 1, models.Farmer.created_at <= report_year).all() response['total_of_farmer'] += len(fs) response['total_of_male'] += len(males) response['total_of_female'] = \ response['total_of_farmer'] - response['total_of_male'] return json.dumps(response)
def resolve_permissions( self, user, project_id: fields.Integer(minimum=1) ) -> fields.List(fields.String()): permissions = (UserPermissionLinker.query.filter_by( project_id=project_id, user_id=user.id).join( UserPermissionLinker.permission).with_entities( Permission.slug).all()) permissions = list(map(lambda x: x.slug, permissions)) return permissions
def rate_trip(self, trip, classification: fields.Integer(nullable=False), score: fields.Integer(nullable=False, minimum=1, maximum=5)): """List all trips of an User Returns: boolean: True if values are set correctly """ if trip.user_id != current_identity.id: raise Forbidden('You are not allowed to rate this trip') trip.classification = classification trip.score = score db.session.add(trip) try: db.session.commit() except Exception as e: logger.exception(e) db.session.rollback() return True
class Schema(object): textId = fields.String(description='The string id of an indicator', attribute='text_id') text = fields.String(description='Indicator description text', attribute='text') groupId = fields.Integer(description='Indicator group ID', attribute='group_id', io='w') indicatorGroup = fields.ToOne('indicator_groups', attribute='indicator_group', io='r') constituents = fields.ToMany( 'web.server.api.indicator_api_models.IndicatorResource')
def billing( self, client, month: fields.Integer(minimum=1, maximum=12)) -> fields.Any(): now = datetime.datetime.utcnow() _, stop_day = calendar.monthrange(now.year, month) start = datetime.datetime(now.year, month, 1, 1, 1, 1) stop = datetime.datetime(now.year, month, stop_day, 23, 59, 59) res = {'sum': 0, 'projects': []} for project in client.projects: p = {'name': project.name, 'duration': 0} for entry in project.workentries.filter(WorkEntry.start >= start, WorkEntry.start <= stop): p['duration'] += entry.duration res['projects'].append(p) res['sum'] += p['duration'] return res
from flask_potion import Api, ModelResource, fields app = Flask(__name__) db = SQLAlchemy(app) class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(), nullable=False) year_published = db.Column(db.Integer) db.create_all() class BookResource(ModelResource): class Meta: model = Book class Schema: year_published = fields.Integer(minimum=1400) BookResource.schema.set('$id', fields.Integer(attribute='id', nullable=True)) api = Api(app) api.add_resource(BookResource) if __name__ == '__main__': app.run()
roles = resources.get(resource_name, []) roles.append(role_name) resources[resource_name] = roles if resource_type not in output: output[resource_type] = roles_by_resource_type return output '''The schema of the `Permission` model. ''' PERMISSION_SCHEMA = alchemy_fields.InlineModel( { 'id': fields.Integer(minimum=1, description='The ID of the permission.'), 'permission': fields.String(description='The type of permission.'), }, title='Permission', description='An individual role permission.', model=Permission, ) '''The schema for the `ResourceType` model. ''' RESOURCE_TYPE_FIELDS = { 'id': fields.Integer(minimum=1, description='The id of the resource type.'), 'name': fields.String( description='The string representation of the resource type.'), }
description='The last time the dashboard was accessed (if ever) by the current user.', nullable=True, attribute='last_accessed_by_user', io='r', ) LAST_MODIFIED_BY_USER_SCHEMA = fields.DateTimeString( description='The last time the dashboard was edited (if ever) by the current user.', nullable=True, attribute='last_modified_by_user', io='r', ) TOTAL_VIEWS_BY_USER_SCHEMA = fields.Integer( description='The total number of times the current user has viewed the dashboard.', minimum=0, attribute='total_views_by_user', io='r', ) TOTAL_VIEWS_SCHEMA = fields.Integer( description='The total number of times the dashboard has been viewed.', minimum=0, attribute='total_views_real', io='r', ) DASHBOARD_BASE_FIELDS = { '$uri': fields.ItemUri( 'web.server.api.dashboard_api_models.DashboardResource', attribute='resource_id' ), 'title': TITLE_SCHEMA,
class Schema: id = fields.Integer(io='r')
class Schema: network = fields.ToOne('networks') gateway = fields.ToOne('gateways') available_actions = fields.String() time_left = fields.Integer()
def add_view(self, video) -> FieldSet({'count': fields.Integer(), 'view': fields.Inline(ViewResource)}): '''Create view and return view and count''' view = ViewResource().manager.create({ 'video_id': video.id }) return {'count': video.count, 'view': view}
class Schema: field_b = fields.Integer(io='r') field_c = fields.Integer(io='r')
class Schema: id = fields.Integer(io='r') user = ToOneIntegerField(UserResource) task = ToOneIntegerField(TaskResource) timestamp = fields.DateTimeString(io='r')
class Schema: queryUuid = fields.String(attribute='query_uuid', nullable=True) userId = fields.Integer(attribute='user_id') queryBlob = fields.Any(attribute='query_blob')
class RoleResource(PrincipalResource): '''The potion class for performing CRUD operations on the `Role` class. ''' resourceType = Relation('resource-type', attribute='resource_type', io='r') class Meta(object): model = Role natural_key = 'name' # Read Permissions are the defaults as defined in # `web.server.security.permissions.PERMISSION_DEFAULTS` # # Create, Update and Delete Permissions are enforced by the # Signal Handlers installed when the API for this Resource # are initialized in `web.server.security.signal_handlers.py` filters = { 'name': True, 'resourceType': { None: ResourceTypeFilter, 'eq': ResourceTypeFilter }, } class Schema(object): permissions = fields.List( PERMISSION_SCHEMA, title='Role Permissions', description='The permissions the role has.', ) resourceType = fields.Custom( fields.String(), attribute='resource_type', converter=None, formatter=lambda rsc_type: rsc_type.name.name, title='resourceType', description='The resource type this role is associated with.', io='r', ) # pylint: disable=E1101 @ItemRoute.PATCH( '/permissions', title='Update Role Permissions', description= 'Updates the role\'s permissions with the values specified.', rel='updatePermissions', schema=fields.List( PERMISSION_SCHEMA, title='Updated Permissions', description='The updated role permissions.', ), ) def update_role_permissions(self, role, new_permissions): with AuthorizedOperation('update_permissions', 'role', role.id): self.manager.update(role, {'permissions': new_permissions}) return None, NO_CONTENT @ItemRoute.POST( '/permission', title='Add Role Permission', description='Adds a single permission to a Role.', rel='addPermission', schema=FieldSet({ 'permissionId': fields.Integer( description= 'The id of the new permission to be added to this role.') }), response_schema=UPDATE_ROLE_PERMISSIONS_RESPONSE_SCHEMA, ) def add_single_permision(self, role, permissionId): with AuthorizedOperation('update_permissions', 'role', role.id): new_permission = find_by_id(Permission, permissionId) if not new_permission: raise ItemNotFound('permission', id=permissionId) if new_permission.resource_type_id != role.resource_type_id: error_message = ( 'The resource type associated with the permission ' 'must match the resource type of the role.') return ( StandardResponse( error_message, BAD_REQUEST, False, roleResourceType=new_permission.resource_type, permissionResourceType=role.resource_type, ), BAD_REQUEST, ) exists = True if new_permission not in role.permissions: exists = False role.permissions.append(new_permission) self.manager.update(role, {'permissions': role.permissions}) added_message = 'already exists for' if exists else 'has been added' success_message = 'Permission \'%s\' %s to Role \'%s\'.' % ( new_permission.permission, added_message, role.name, ) return StandardResponse(success_message, OK, True) @ItemRoute.DELETE( '/permission', title='Delete Role Permission', description='Deletes a single permission from a role.', schema=FieldSet({ 'permissionId': fields.Integer( description= 'The id of the new permission to be deleted from this role.') }), response_schema=UPDATE_ROLE_PERMISSIONS_RESPONSE_SCHEMA, rel='deletePermission', ) def delete_individual_permission(self, role, permissionId): with AuthorizedOperation('update_permissions', 'role', role.id): old_permission = find_by_id(Permission, permissionId) if not old_permission: raise ItemNotFound('permission', id=permissionId) if old_permission.resource_type_id != role.resource_type_id: error_message = ( 'The resource type associated with the permission ' 'must match the resource type of the role.') return ( StandardResponse( error_message, BAD_REQUEST, False, roleResourceType=old_permission.resource_type, permissionResourceType=role.resource_type, ), BAD_REQUEST, ) exists = True try: role.permissions.remove(old_permission) self.manager.update(role, {'permissions': role.permissions}) except ValueError: exists = False deleted_message = ('has been removed from' if exists else 'does not exist for') success_message = 'Permission \'%s\' %s Role \'%s\'.' % ( old_permission.permission, deleted_message, role.name, ) return StandardResponse(success_message, OK, True)
class Schema: telegram_id = fields.Integer()
def rating(self, book) -> fields.Integer(): return book.rating
class Schema: published = fields.DateString() count = fields.Integer()
def rate( self, book, value: fields.Integer(minimum=1, maximum=10)) -> fields.Integer(): self.manager.update(book, {"rating": value}) return value
def view_count(self, video, date: fields.DateString(nullable=True)) -> fields.Integer(): return video.views.filter(models.View.created_at >= date).count() if date else video.count
def __init__(self, description, code, success, **additional_fields): super(StandardResponse, self).__init__() self['message'] = description self['code'] = code self['success'] = success for key, value in list(additional_fields.items()): self[key] = value STANDARD_RESPONSE_FIELDS = { 'success': fields.Boolean( description='Indicates whether the requested operation was successful or not.', nullable=True, ), 'message': fields.String(min_length=1, description='The response from the server.'), 'code': fields.Integer(description='The HTTP response code from the server.'), } STANDARD_RESPONSE_SCHEMA = FieldSet(STANDARD_RESPONSE_FIELDS) def augment_standard_schema(additional_fields): '''Augments the schema of the `StandardResponse` class with additional fields that are to be included in the response to an API request. Example ---------- ``` # The `StandardResponse` has 3 attributes: `success`, `description` and `code`. I wish to # return a field named `foo_bar` as well in the response object.
class Schema: year_published = fields.Integer(minimum=1400)
class Schema: id = fields.Integer(io='r') bids = ToManyIntegerField('bids')