class PlaySchema(Schema): action = fields.Nested(ActionSchema) player = fields.Pluck(PlayerStatusSchema, "position") discarding_player = fields.Pluck( PlayerStatusSchema, "position", data_key="discardingPlayer" ) discard = fields.Pluck(CardSchema, "value")
class EpisodeStrictSchema(EpisodeSchema): """ Strict schema for :class:`aliceplex.schema.model.Episode` """ title = fields.List( fields.Str(allow_none=False), validate=Length(min=1), allow_none=False, required=True ) aired = fields.Date(allow_none=True) content_rating = fields.Str(allow_none=False, required=True) summary = fields.Str(allow_none=False, required=True) directors = fields.List( fields.Pluck(PersonStrictSchema, "name", allow_none=False), allow_none=False, required=True ) writers = fields.List( fields.Pluck(PersonStrictSchema, "name", allow_none=False), allow_none=False, required=True ) rating = fields.Float(validate=Range(min=0, max=10), allow_none=True)
class SeanceSchema(ma.SQLAlchemyAutoSchema): class Meta: model = SeanceModel include_fk = True movie = fields.Pluck(lambda: MovieSchema, 'title') hall = fields.Pluck(lambda: HallSchema, 'name')
class MovieSchema(DataClassSchema): """ Schema for :class:`aliceplex.schema.model.Movie` """ title = fields.Str(allow_none=True) sort_title = fields.Str(allow_none=True) original_title = fields.Str(allow_none=True) content_rating = fields.Str(allow_none=True) tagline = fields.List(fields.Str(allow_none=False), allow_none=False) studio = fields.List(fields.Str(allow_none=False), allow_none=False) aired = fields.Date(allow_none=True) summary = fields.Str(allow_none=True) rating = fields.Float(validate=Range(min=0, max=10), allow_none=True) genres = fields.List(fields.Str(allow_none=False), allow_none=False) collections = fields.List(fields.Str(allow_none=False), allow_none=False) actors = fields.List( fields.Nested(ActorSchema, allow_none=False), allow_none=False ) writers = fields.List( fields.Pluck(PersonSchema, "name", allow_none=False), allow_none=False ) directors = fields.List( fields.Pluck(PersonSchema, "name", allow_none=False), allow_none=False ) @property def data_class(self) -> type: return Movie
class ObservationSchema(Schema): players = fields.List(fields.Nested(PlayerStatusSchema)) curr_player = fields.Pluck(PlayerStatusSchema, "position", data_key="currentPlayer") hand = fields.Method("get_human_player_hand") priestInfo = fields.Method("get_priest_info") discard = fields.List(fields.Pluck(CardSchema, "value")) cardsRemaining = fields.Method("get_cards_remaining") plays = fields.List(fields.Nested(PlaySchema)) validActions = fields.Method("get_valid_actions") game_over = fields.Boolean(data_key="gameOver") winners = fields.List(fields.Pluck(PlayerStatusSchema, "position")) def get_human_player_hand(self, obj): return [card.value for card in obj.players[0].hand if card != Card.EMPTY] def get_cards_remaining(self, obj): return obj.deck.remaining() def get_priest_info(self, obj): return PriestInfoSchema().dump(obj.players[0])["_priest_targets"] def get_valid_actions(self, obj): if obj.curr_player.position != 0: return [] return ActionSchema().dump(obj.valid_actions, many=True)
class MachineSchema(SQLAlchemyAutoSchema): class Meta: model = Machine load_instance = True exclude = ("id", ) os = fields.Pluck(OSSchema, "id") file = fields.Pluck(FileSchema, "name", many=True)
class TagItemSchema(Schema): id = fields.Integer(dump_only=True) contact_id = fields.Integer(required=True) tag_id = fields.Integer(required=True) name = fields.Pluck(TagSchema, 'name', attribute='tag', dump_only=True) type = fields.Pluck(TagSchema, 'type', attribute='tag', dump_only=True) score = fields.Integer() #Decimal() throws an error in python 3.7 class Meta: unknown = EXCLUDE
class UserSchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """This is the schema for the User model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the User fields to a default schema.""" model = UserModel exclude = ('id',) contacts = fields.Pluck('ContactLinkSchema', 'contact', many=True) orgs = fields.Pluck('MembershipSchema', 'org', many=True)
class UserSchema(LoginSchema): """Serializes and deserializes User objects.""" id = fields.Integer() registered_on = fields.DateTime(dump_only=True) roles = fields.Pluck("RoleSchema", "name", many=True) permissions = fields.Pluck("PermissionSchema", "name", many=True) @post_load def load_user(self, data, **kwargs): """Create a user object using the deserialized values.""" return User(**data)
class GroupMemberSchema(Schema): class Meta: ordered = True id = fields.Int() tournament_id = fields.Int() runner = fields.Pluck(UserSchema, "username", attribute="user") group_name= fields.Pluck(GroupNameSchema, "group_name", attribute="group") @post_load def make_group(self, data, **kwargs): return GroupMember(**data)
class OrgSchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """This is the schema for the Org model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the Org fields to a default schema.""" model = OrgModel contacts = fields.Pluck('ContactLinkSchema', 'contact', many=True) members = fields.Pluck('MembershipSchema', 'user', many=True) affiliated_entities = fields.Pluck('AffiliationSchema', 'entity', many=True, data_key='affiliatedEntities')
class MovieStrictSchema(MovieSchema): """ Strict schema for :class:`aliceplex.schema.model.Movie` """ title = fields.Str(allow_none=False, required=True) sort_title = fields.Str(allow_none=False, required=True) original_title = fields.Str(allow_none=False, required=True) content_rating = fields.Str(allow_none=False, required=True) tagline = fields.List( fields.Str(allow_none=False), allow_none=False, required=True ) studio = fields.List( fields.Str(allow_none=False), validate=Length(min=1), allow_none=False, required=True ) aired = fields.Date(allow_none=False, required=True) summary = fields.Str(allow_none=False, required=True) rating = fields.Float(validate=Range(min=0, max=10), allow_none=False) genres = fields.List( fields.Str(allow_none=False), validate=Length(min=1), allow_none=False, required=True ) collections = fields.List( fields.Str(allow_none=False), validate=Length(min=1), allow_none=False, required=True ) actors = fields.List( fields.Nested(ActorSchema, allow_none=False), validate=Length(min=1), allow_none=False, required=True ) writers = fields.List( fields.Pluck(PersonStrictSchema, "name", allow_none=False), allow_none=False, required=True ) directors = fields.List( fields.Pluck(PersonStrictSchema, "name", allow_none=False), allow_none=False, required=True )
class TeamSchema(Schema): """This class manages project users(developer,manager,cto) request and response schema.""" class Meta: # pylint: disable=too-few-public-methods """Exclude unknown fields in the deserialized output.""" unknown = EXCLUDE id = fields.Int() project_id = fields.Int(data_key='projectId') user_id = fields.Int(data_key='userId') role = fields.Int(data_key='role', required=True, validate=validate.OneOf(list(map(int, ProjectRoles)))) email = fields.Email(load_only=True, required=True, validate=validate.Length(min=5, max=250)) phone = fields.Str(load_only=True, allow_none=True, validate=validate.Length(max=15)) first_name = fields.Str(load_only=True, data_key='firstName', required=True, validate=validate.Length(max=250)) last_name = fields.Str(load_only=True, data_key='lastName', required=True, validate=validate.Length(max=250)) # Since the user data has to be plucked, seperating load and dump into different fields. dump_email = fields.Pluck(UserSchema, field_name='email', dump_only=True, data_key='email', attribute='user') dump_phone = fields.Pluck(UserSchema, field_name='phone', dump_only=True, data_key='phone', attribute='user') dump_first_name = fields.Pluck(UserSchema, field_name='first_name', dump_only=True, data_key='firstName', attribute='user') dump_last_name = fields.Pluck(UserSchema, field_name='last_name', dump_only=True, data_key='lastName', attribute='user')
class PlayerSchema(SQLAlchemyAutoSchema): hug_counter = fields.Method("get_hug_count", dump_only=True) playtime = fields.Method("get_playtime", dump_only=True) faction = fields.Pluck("FactionSchema", "id", many=False) def get_hug_count(self, player) -> int: return Hug.query.filter_by(player=player).count() def get_playtime(self, player): first_hug = Hug.query.filter_by(player=player).order_by( asc('timestamp')).first() last_hug = Hug.query.filter_by(player=player).order_by( desc('timestamp')).first() if not (first_hug and last_hug): return None return (last_hug.timestamp - first_hug.timestamp).total_seconds() class Meta: # Regular players won't be able to access other player's schema, so we can safely dump the is_admin exclude = ['id', 'hugs'] dump_only = ['faction'] model = Player include_relationships = True load_instance = True include_fk = False
class RevissionDeviceSchema(Schema): id = fields.Int() name = fields.Str() id_location = fields.Int() id_category = fields.Int() id_acc_center = fields.Str() location = fields.Pluck(LocationsSchemaNested, 'id_acc_center')
class PonySchema(SQLAlchemyAutoSchema): first_hug = fields.Method("get_first_hug", dump_only=True) hugs = fields.Pluck('HugSchema', 'player', many=True, dump_only=True) key = fields.String(required=True, validate=[Length(equal=10), Regexp(r"^[0-9A-Z]*$")]) def get_first_hug(self, pony) -> Optional[Dict[str, str]]: first_hug_for_this_pony = Hug.query.filter_by(pony=pony).order_by( asc('timestamp')).first() if not first_hug_for_this_pony: return None return { "playername": first_hug_for_this_pony.player.name, "timestamp": first_hug_for_this_pony.timestamp } class Meta: load_only = ['key'] model = Pony include_relationships = True load_instance = True include_fk = True
class Comment(Schema): author = fields.Pluck( 'User', 'username', dump_only=True ) article = fields.Pluck( 'Article', 'title', dump_only=True ) body = fields.Str( required=True, error_messages={'required': 'Body is required.'} )
class OrgSchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """This is the schema for the Org model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the Org fields to a default schema.""" model = OrgModel exclude = ('members', 'invitations', 'affiliated_entities', 'suspension_reason', 'products', 'login_options', 'type_code') type_code = fields.String(data_key='org_type') status_code = fields.String(data_key='status_code') suspension_reason_code = fields.String(data_key='suspension_reason_code') business_size = fields.String(data_key='business_size') business_type = fields.String(data_key='business_type') contacts = fields.Pluck('ContactLinkSchema', 'contact', many=True, data_key='mailing_address') @post_dump(pass_many=False) def _include_dynamic_fields(self, data, many): # pylint: disable=no-self-use """Remove all empty values and versions from the dumped dict.""" if not many: if data.get('is_business_account', False): # Adding a dynamic field businessName for making other application integrations easy. data['businessName'] = data.get('name') # Map the mailing address to the first from contact as there can be only one mailing address. if (mailing_address := data.get( 'mailing_address', None)) is not None and mailing_address: data['mailing_address'] = mailing_address[0] return data
class DealerOutputSchema(ma.Schema): class Meta: model = Dealer fields = ( "public_id", "internal_id", "brand", "name", "phone", "email", "website", "street_address", "city", "state", "postal_code", "country", "latitude", "longitude", "sales_hours", "service_hours", "services", ) ordered = True sales_hours = ma.Nested("HoursSchema", many=True) service_hours = ma.Nested("HoursSchema", many=True) services = fields.Pluck("DealerServiceSchema", "service", many=True)
class GroupSchema(Schema): id = fields.Integer(dump_only=True, required=True, validate=Range(min=1)) name = fields.String(required=True, validate=Length(min=1)) description = fields.String(required=True, validate=Length(min=1)) group_type_id = fields.Integer(data_key='groupTypeId', required=True) active = fields.Boolean(required=True) members = fields.Nested('MemberSchema', dump_only=True, many=True, only=['person', 'active']) managers = fields.Nested('ManagerSchema', dump_only=True, many=True, only=['person', 'active', 'manager_type']) meetings = fields.Nested('MeetingSchema', dump_only=True, many=True, only=[ 'group_id', 'address_id', 'start_time', 'stop_time', 'description', 'active', 'attendances' ]) images = fields.Pluck('ImageGroupSchema', 'image', many=True) group_type = fields.Nested('GroupTypeSchema', dump_only=True, data_key='groupType', only=['id', 'name']) member_histories = fields.Nested('MemberHistorySchema', many=True, dump_only=True, data_key='memberHistories', only=('id', 'time', 'is_join', 'person_id'))
class FragmentSchema(Schema): number = fields.Nested(MuseumNumberSchema, required=True, data_key="museumNumber") accession = fields.String(required=True) cdli_number = fields.String(required=True, data_key="cdliNumber") bm_id_number = fields.String(required=True, data_key="bmIdNumber") publication = fields.String(required=True) description = fields.String(required=True) collection = fields.String(required=True) script = fields.String(required=True) museum = fields.String(required=True) width = fields.Nested(MeasureSchema, required=True) length = fields.Nested(MeasureSchema, required=True) thickness = fields.Nested(MeasureSchema, required=True) joins = fields.Pluck(JoinsSchema, "fragments", load_default=Joins()) record = fields.Pluck(RecordSchema, "entries") folios = fields.Pluck(FoliosSchema, "entries") text = fields.Nested(TextSchema) signs = fields.String(load_default="") notes = fields.String(required=True) references = fields.Nested(ReferenceSchema, many=True, required=True) uncurated_references = fields.Nested( UncuratedReferenceSchema, many=True, data_key="uncuratedReferences", load_default=None, ) genres = fields.Nested(GenreSchema, many=True, load_default=tuple()) line_to_vec = fields.List( fields.List(ValueEnum(LineToVecEncoding)), load_default=tuple(), data_key="lineToVec", ) @post_load def make_fragment(self, data, **kwargs): data["references"] = tuple(data["references"]) data["genres"] = tuple(data["genres"]) data["line_to_vec"] = tuple(map(tuple, data["line_to_vec"])) if data["uncurated_references"] is not None: data["uncurated_references"] = tuple(data["uncurated_references"]) return Fragment(**data) @post_dump def filter_none(self, data, **kwargs): return pydash.omit_by(data, pydash.is_none)
class ResponseSchema(Schema): class Meta: ordered = True id = fields.Int() question_id = fields.Int() user_id = fields.Int() username = fields.Pluck(UserSchema, "username", attribute="user") question = fields.Pluck(QuestionSchema, "question", attribute="question") response = fields.Str() date_created = fields.DateTime() date_modified = fields.DateTime() @post_load def make_response(self, data, **kwargs): return Response(**data)
class VisitSchema(ma.SQLAlchemyAutoSchema): booked_location = fields.Nested(LocationSchema, attribute="location") specialization = fields.Nested(SpecializationSchema) locations = fields.Pluck(VisitToLocationSchemaForVisits, "location", many=True) time_frames = fields.Nested(TimeFrameSchema, many=True) user = fields.Nested(UserSchemaSimple) class Meta: model = Visit
class AgentWithWorkspacesSchema(AgentSchema): workspaces = fields.Pluck(WorkspaceSchema, "name", many=True, required=True) class Meta(AgentSchema.Meta): fields = AgentSchema.Meta.fields + ('workspaces', )
class HugSchema(SQLAlchemyAutoSchema): player = fields.Pluck('PlayerSchema', 'name', many=False) pony = fields.Nested('PonySchema', many=False) class Meta: model = Hug include_relationships = True load_instance = True include_fk = False
class ProductSubscriptionSchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """This is the schema for the ProductSubscription model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the ProductSubscription fields to a default schema.""" model = ProductSubscriptionModel product_role_type = fields.Pluck('ProductSubscriptionRoleSchema', 'code', data_key='product_subscription_role')
class AffidavitSchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """This is the schema for the affidavit model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the affidavit fields to a default schema.""" model = AffidavitModel exclude = ('id', ) contacts = fields.Pluck('ContactLinkSchema', 'contact', many=True)
def test_many_with_property(self): breed = fields.Pluck(CategorySchema, "breed", many=True, dump_only=True) assert self.field2property(breed) == { "items": self.unplucked, "type": "array", "readOnly": True, }
class FilterOutputSchema(Schema): id = fields.Integer(dump_only=True) first_name = fields.String(dump_only=True) last_name = fields.String(dump_only=True) email = fields.String(dump_only=True) status = EnumField(ContactStage, dump_only=True) phone_primary = fields.String(dump_only=True) years_exp = fields.Pluck(ProfileSchema, 'years_exp', attribute='profile', dump_only=True) job_search_status = fields.Pluck(ProfileSchema, 'job_search_status', attribute='profile', dump_only=True) programs_interested = fields.Pluck(ProgramAppSchema, 'program_name', many=True, data_key='programs')
class EntitySchema(BaseSchema): # pylint: disable=too-many-ancestors, too-few-public-methods """Used to manage the default mapping between JSON and the Entity model.""" class Meta: # pylint: disable=too-few-public-methods """Maps all of the Entity fields to a default schema.""" model = EntityModel exclude = ('id', 'pass_code') contacts = fields.Pluck('ContactLinkSchema', 'contact', many=True) corp_type = fields.Nested(CorpTypeSchema, many=False)