class WorkshopModel(db.Document): """ This is an abstract class. Please inherit from it if you want to create a new type of workshop """ meta = {"collection": "workshops"} workshopId = db.StringField(primary_key=True, default=generate_id) name = db.StringField(required=True, max_length=128, min_length=1, default="Atelier CAPLC") createdAt = db.DateTimeField(default=datetime.datetime.utcnow) updatedAt = db.DateTimeField(default=datetime.datetime.utcnow) startAt = db.DateTimeField(required=True) creatorId = db.StringField(required=True) coachId = db.StringField(required=True) eventUrl = db.StringField(default="caplc.com") city = db.StringField(max_length=128, min_length=1) address = db.StringField(max_length=512) participants = db.ListField( db.EmbeddedDocumentField(WorkshopParticipantModel), default=[]) model = db.ReferenceField(Model, db_field="modelId") def __repr__(self): return ( f"<Workshop {self.workshopId} | {self.name} " f"- animated by {self.coachId} at {self.city} on {self.startAt} " f"- with {len(self.participants)} participants>") @classmethod def find_by_id(cls, workshop_id: str) -> WorkshopModel: try: workshop = cls.objects.get(workshopId=workshop_id) except db.DoesNotExist: workshop = None return workshop @classmethod def find_by_coach_id(cls, coach_id: str) -> WorkshopModel: try: workshops = cls.objects(coachId=coach_id) except db.DoesNotExist: workshops = [] return workshops def get_participant_ids(self) -> list: return [p.user.id for p in self.participants] def get_workshop_participant(self, participant_id: str): for workshop_participant in self.participants: if workshop_participant.user.id == participant_id: return workshop_participant return None
class Role(db.Document): name = db.StringField(max_length=255, required=True, unique=True) description = db.StringField(max_length=255) permissions = db.ListField(db.ReferenceField(Permission), default=[]) def __str__(self): return self.description def __unicode__(self): return self.description
class User(db.Document): username = db.StringField(max_length=255, verbose_name='用户名称', required=True, unique=True) _password = db.StringField(max_length=255, verbose_name='用户密码') active = db.BooleanField(default=True, verbose_name='当前账户是否激活') create_time = db.DateTimeField(default=datetime.datetime.now, verbose_name='创建时间') roles = db.ListField(db.ReferenceField(Role), default=[]) # 给这个用户增加角色 def add_role(self, role_names: list): for role_name in role_names: role = Role.objects(name=role_name).first() if not role: role = Role(name=role_name) role.save() self.roles.append(role) self.roles = list(set(self.roles)) @staticmethod def register(username, password): new_user = User(username=username, _password=generate_password_hash(password)) new_user.save() return new_user @property def password(self): return self._password @password.setter def password(self, passwd): self._password = generate_password_hash(passwd) def check_password(self, raw): return check_password_hash(self._password, raw) def __unicode__(self): return str(self.username)
class ShareModel(db.Document): adminId = db.ReferenceField(AdminModel, required=True) created_at = db.DateTimeField(default=datetime.datetime.utcnow, required=True) title = db.StringField(required=True) content = db.StringField(required=True) meta = { 'collection': 'share', 'indexes': ['-created_at'], 'ordering': ['-created_at'] } # 添加一个资源 @staticmethod def add_share(data): adminId = ObjectId(data['adminId']) title = data['title'] content = data['content'] share = ShareModel(adminId=adminId, title=title, content=content) share.save() # 修改一个资源 @staticmethod def put_share(id, data): id = ObjectId(id) adminId = ObjectId(data['adminId']) title = data['title'] content = data['content'] share = ShareModel.objects(id=id) share.update(adminId=adminId, title=title, content=content) # 删除一个资源 @staticmethod def delete_share(id): id = ObjectId(id) share = ShareModel.objects(id=id) share.delete()
class UserModel(db.Document): # _id = db.StringField() wxId = db.StringField(required=True) name = db.StringField(required=True) avatar = db.StringField(required=True) schoolId = db.StringField(required=True) classId = db.ReferenceField(ClassModel) meta = {'collection': 'user', 'ordering': ['name', 'schoolId']} # 添加一个用户 @staticmethod def add_user(data): wxId = data['wxId'] + current_app.config['SECRET_KEY'] m = hashlib.md5() m.update(wxId.encode("utf8")) wxId = m.hexdigest() clsId = ObjectId(data['classId']) user = UserModel(wxId=wxId, name=data['name'], avatar=data['avatar'], schoolId=data['schoolId'], classId=clsId) user.save() # 给对应班级添加人数 ClassModel.objects(id=clsId).update_one(inc__stuNum=1) # 通过 objectId 获取用户信息 @staticmethod def get_user(id): user = UserModel.objects(id=ObjectId(id)).first() if not user: raise FormValidateError(msg='用户不存在') dic = { 'id': str(user['id']), 'name': user['name'], 'avatar': user['avatar'], 'schoolId': user['schoolId'], 'classroom': str(user['classId']['name']) } return dic # 修改用户信息 @staticmethod def put_user(id, data): user = UserModel.objects(id=ObjectId(id)) origin_classId = str(user[0]['classId']['id']) user.update(name=data['name'], avatar=data['avatar'], schoolId=data['schoolId'], classId=ObjectId(data['classId'])) # 如果换了班级,则修改班级人数 if origin_classId != str(data['classId']): ClassModel.objects(id=ObjectId(origin_classId)).update_one( dec__stuNum=1) ClassModel.objects(id=ObjectId(data['classId'])).update_one( inc__stuNum=1) # 通过用户id删除用户 @staticmethod def delete_user(id): user = UserModel.objects(id=ObjectId(id)) clsId = user[0]['classId']['id'] user.delete() # 给对应班级减去人数 ClassModel.objects(id=clsId).update_one(dec__stuNum=1)
class CommentModel(db.Document): userId = db.ReferenceField(UserModel, required=True) topicId = db.ReferenceField(TopicModel, required=True) created_at = db.DateTimeField(default=datetime.datetime.utcnow, required=True) content = db.StringField(required=True) meta = { 'collection': 'comment', 'indexes': ['-created_at'], 'ordering': ['-created_at'] } # 创建评论 @staticmethod def add_comment(data): userId = ObjectId(data['userId']) topicId = ObjectId(data['topicId']) content = data['content'] comment = CommentModel(userId=userId, topicId=topicId, content=content) comment.save() # 修改评论 @staticmethod def put_comment(data): id = ObjectId(data['id']) content = data['content'] comment = CommentModel.objects(id=id) comment.update(content=content) # 删除评论 @staticmethod def delete_comment(id): id = ObjectId(id) comment = CommentModel.objects(id=id) comment.delete() # 获取评论 @staticmethod def get_comment_list(data): topicId = ObjectId(data['topicId']) page = int(data['page']) size = int(data['size']) count = CommentModel.objects(topicId=topicId).count() comments = CommentModel.objects( topicId=topicId).order_by('-created_at').skip( (page - 1) * size).limit(size) list = [] for comment in comments: list.append({ 'id': str(comment['id']), 'created_at': comment['created_at'], 'userId': str(comment['userId']['id']), 'userName': str(comment['userId']['name']), 'schoolId': str(comment['userId']['schoolId']), 'avatar': str(comment['userId']['avatar']), 'className': str(comment['userId']['classId']['name']), 'content': comment['content'] }) res = { 'list': list, 'pagination': { 'count': count, 'size': size, 'page': page } } return res
class SignModel(db.Document): name = db.StringField(required=True) adminId = db.ReferenceField(AdminModel) classroomIds = db.ListField(db.ReferenceField(ClassModel)) signUsers = db.ListField(db.ReferenceField('UserModel'), default=[]) token = db.StringField(required=True) created_at = db.DateTimeField(default=datetime.datetime.utcnow, required=True) meta = { 'collection': 'sign', 'indexes': ['-created_at'], 'ordering': ['-created_at'], 'strict': False } # 保存签到表到数据库 @staticmethod def add_sign(data): name = data['name'] adminId = ObjectId(data['adminId']) classroomIds = [] for cls in data['classroomIds'].split('|'): classroomIds.append(ObjectId(cls)) token = data['token'] sign = SignModel(name=name, adminId=adminId, classroomIds=classroomIds, token=token) sign.save() return str(sign['id']) # 学生签到 @staticmethod def user_sign(token, userId): userId = ObjectId(userId) sign = SignModel.objects(token=token) sign.update_one(add_to_set__signUsers=userId) # 老师帮学生签到 @staticmethod def super_user_sign(signId, signUsers): signId = ObjectId(signId) sign = SignModel.objects(id=signId) sign.update_one(add_to_set__signUsers=signUsers) # 老师手动删除签到 @staticmethod def super_delete_user_sign(signId, signUsers): signId = ObjectId(signId) sign = SignModel.objects(id=signId) sign.update_one(pull_all__signUsers=signUsers) # 获取签到表列表 @staticmethod def get_sign_list(page, size, classId): if classId is not None: classId = ObjectId(classId) cls = ClassModel.objects(id=classId).first() if cls: clss = SignModel.objects( classroomIds__in=[classId]).order_by('-created_at').skip( (page - 1) * size).limit(size) count = SignModel.objects(classroomIds__in=[classId]).count() else: clss = [] count = 0 else: clss = SignModel.objects().order_by('-created_at').skip( (page - 1) * size).limit(size) count = SignModel.objects().count() data = [] for cls in clss: classrooms = [] for room in cls['classroomIds']: classrooms.append({ 'id': str(room['id']), 'name': room['name'], 'stuNum': room['stuNum'] }) data.append({ 'id': str(cls['id']), 'name': cls['name'], 'adminName': cls['adminId']['name'], 'classrooms': classrooms, 'created_at': cls['created_at'] }) res = { 'pagination': { 'count': count, 'size': size, 'page': page }, 'list': data } return res # 删除签到表 @staticmethod def delete_sign(signId): signId = ObjectId(signId) sign = SignModel.objects(id=signId) sign.delete()
class WorkshopParticipantModel(db.EmbeddedDocument): user = db.ReferenceField(UserModel, db_field="userId") status = db.StringField(max_length=32)