class ClassModel(db.Document): name = db.StringField(required=True) stuNum = db.IntField(default=0) meta = {'collection': 'class'} # 添加一个班级 @staticmethod def add_classroom(name): cls = ClassModel(name=name) cls.save() # 修改班级 @staticmethod def put_classroom(id, name): id = ObjectId(id) cls = ClassModel.objects(id=id) cls.update(name=name) # 删除班级 @staticmethod def delete_classroom(id): id = ObjectId(id) cls = ClassModel.objects(id=id) cls.delete()
class ActionCardModel(db.Document): meta = {"collection": "actionCards"} actionCardId = db.StringField(primary_key=True, default=generate_id) cardNumber = db.IntField(required=True, min_value=0) name = db.StringField(required=True) category = db.StringField(required=True) type = db.StringField(required=True) key = db.StringField(required=True) sector = db.StringField(required=True) cost = db.IntField(required=True, min_value=0) createdAt = db.DateTimeField(default=datetime.datetime.utcnow) updatedAt = db.DateTimeField(default=datetime.datetime.utcnow) @classmethod def find_all(cls): return cls.objects().order_by("number")
class User(db.Document, UserMixin): first_name = db.StringField(required=True) last_name = db.StringField(required=True) email = db.StringField(required=True, unique=True) password_hash = db.StringField(required=True) course_type = db.StringField(choices=COURSE_TYPES + NULL_CHOICE) course_date = db.StringField(choices=COURSE_DATES + NULL_CHOICE) country_origin = db.StringField() company = db.StringField() employment_status = db.StringField() academic_degree = db.StringField() age = db.IntField() entrepreneurial_essay = db.StringField() problem_essay = db.StringField() permissions = db.ListField(db.StringField(choices=PERMISSION_TYPES)) airtable_id = db.StringField() airtable_map = dict(first_name='First Name', last_name='Last Name', course_type='Course Type', company='Company', employment_status='Employment Status', academic_degree='Academic Degree', age='Age', entrepreneurial_essay='Entrepreneurial Essay', problem_essay='Problems Essay') def __str__(self): return f'{self.first_name} {self.last_name}' @property def is_admin(self): return 'admin' in self.permissions
class ColumnZone(Base): meta = { 'increase_key': False, 'collection': 'column_zone', 'ordering': ['-created_at'], 'strict': True, 'id_field': '_id' } _id = db.StringField() name = db.StringField(min_value=2, max_value=50, required=True, unique=True) # 空间标识 title = db.StringField(min_value=2, max_value=50) # 空间名称 user_id = db.IntField(default=0) width = db.IntField(default=0) # 图片宽 height = db.IntField(default=0) # 图片高 kind = db.IntField(default=1) # 类型:1.PC;2.备选;3.-- status = db.IntField(default=1) deleted = db.IntField(default=0) remark = db.StringField() # 备注 created_at = db.DateTimeField() updated_at = db.DateTimeField(default=datetime.datetime.now) # 标记删除 def mark_delete(self): ok = super(ColumnZone, self).update(deleted=1) return ok # 标记恢复 def mark_recovery(self): ok = super(ColumnZone, self).update(deleted=0) return ok def __unicode__(self): return self.name
class Brand(Base): meta = { 'increase_key': True, 'collection': 'brand', 'ordering': ['-created_at'], 'strict': True, 'id_field': '_id' } _id = db.IntField(primary_key=True, required=True) name = db.StringField(min_value=2, max_value=30, required=True, unique=True) # 品牌名称 description = db.StringField() user_id = db.IntField(default=0) kind = db.IntField(default=1) # 类型:1.--;2.--;3.-- cover_id = db.StringField() # 封面ID status = db.IntField(default=1) deleted = db.IntField(default=0) remark = db.StringField() created_at = db.DateTimeField() updated_at = db.DateTimeField(default=datetime.datetime.now) # 封面 def cover(self): if self.cover_id and len(self.cover_id) == 12: asset = Asset.objects(_id=ObjectId(self.cover_id)).first() if asset and asset.deleted == 0: return asset asset = Asset.objects(target_id=str(self._id), asset_type=5, deleted=0).first() if asset and asset.deleted == 0: return asset return None # 标记删除 def mark_delete(self): ok = super(Brand, self).update(deleted=1) if ok: # 删除附件 assets = Asset.objects(target_id=str(self._id), asset_type=5, deleted=0) for item in assets: item.mark_delete() # 标记恢复 def mark_recovery(self): ok = super(Brand, self).update(deleted=0) if ok: # 恢复附件 assets = Asset.objects(target_id=str(self._id), asset_type=5, deleted=1) for item in assets: item.update(deleted=0) def __unicode__(self): return self.name
class Product(db.Document): meta = {'collection': 'Product'} name = db.StringField(required=True) stock = db.IntField(required=True) picture = db.FileField(required=True) price = db.FloatField(required=True) @staticmethod def createProduct(body, picture): try: product = Product.from_json(json.dumps(body), True) product.picture.put(picture, filename=picture.filename.replace(" ", "_"), content_type=picture.content_type) product.save() except Exception as error: print(error) return product @staticmethod def getProduct(id): try: product = Product.objects().get(id=str(id)) data = {} data["id"] = str(product.id) data["name"] = product.name data["stock"] = product.stock data["price"] = product.price data["image"] = {} data["image"]["url"] = f"/api/product/{str(product.id)}/image/{product.picture.filename}" data["image"]["name"] = product.picture.filename except Exception as error: print(error) return data @staticmethod def getImage(id): try: product = Product.objects().get(id=id) file = send_file(io.BytesIO(product.picture.read()), attachment_filename=product.picture.filename, mimetype=product.picture.content_type) except Exception as error: print(error) return file @staticmethod def getAllProducts(): try: products = Product.objects().all() listProducts = [] for product in products : data = {} data["id"] = str(product.id) data["name"] = product.name data["stock"] = product.stock data["price"] = product.price data["image"] = {} data["image"]["url"] = f"/api/product/{str(product.id)}/image/{product.picture.filename}" data["image"]["name"] = product.picture.filename listProducts.append(data) except Exception as error: print(error) return listProducts @staticmethod def updateProduct(id, body, picture): try: updated = { "count": 0 } product = Product.objects().get(id=id) if body["name"]: product.name = body["name"] updated["name"] = "updated" updated["count"] += 1 if body["stock"]: product.stock = int(body["stock"]) updated["stock"] = "updated" updated["count"] += 1 if body["price"]: product.price = float(body["price"]) updated["price"] = "updated" updated["count"] += 1 if picture: product.picture.replace(picture, filename=picture.filename.replace(" ", "_"), content_type=picture.content_type) updated["picture"] = "updated" updated["count"] += 1 product.save() except Exception as error: print(error) return updated @staticmethod def deleteProduct(id): try: product = Product.objects().get(id=str(id)) except Exception as error: product = None print(error) return product
class UserModel(db.Document): meta = {"collection": "users"} # User specific fields userId = db.StringField(primary_key=True, default=generate_id) firstName = db.StringField(required=True, max_length=64, min_length=1) lastName = db.StringField(required=True, max_length=64, min_length=1) email = db.StringField(required=True, max_length=256, unique=True) password = db.StringField() role = db.ListField(db.StringField(max_length=32), required=True) createdAt = db.DateTimeField(default=datetime.datetime.utcnow) updatedAt = db.DateTimeField(default=datetime.datetime.utcnow) # Coach specific fields city = db.StringField(max_length=256) workshopsCount = db.IntField() awarenessRaisedCount = db.IntField() # Participant specific fields workshopParticipations = db.ListField(db.StringField(), default=[]) def __str__(self): return f"User {self.userId} - {self.firstName} {self.lastName}" def __repr__(self): return f"<User {self.userId} - {self.firstName} {self.lastName}>" def allowed(self, access_level: Roles) -> bool: return (max([ACCESS_LEVEL[r] for r in self.role]) >= ACCESS_LEVEL[access_level.value]) def send_reset_password_mail(self) -> str: # Genereate temporary access token for password resetting token = create_access_token(identity=self.id) reset_url = "{url}/reset_password?access_token={token}".format( url=current_app.config["PREFERRED_URL_SCHEME"], token=token) print(token) send_reset_password_mail(self.email, reset_url=reset_url) return token @classmethod def find_by_id(cls, user_id: str) -> UserModel: try: user = cls.objects.get(userId=user_id) except db.DoesNotExist: user = None return user @classmethod def find_by_email(cls, email: str) -> UserModel: try: user = cls.objects.get(email=email) except db.DoesNotExist: user = None return user @classmethod def find_coach_by_id(cls, user_id: str) -> UserModel: try: user = cls.objects.get( userId=user_id, role__in=[Roles.ADMIN.value, Roles.COACH.value]) except db.DoesNotExist: user = None return user @classmethod def find_coach_by_email(cls, email: str) -> UserModel: try: user = cls.objects.get( email=email, role__in=[Roles.ADMIN.value, Roles.COACH.value]) except db.DoesNotExist: user = None return user @classmethod def find_participant_by_email(cls, email: str) -> UserModel: try: user = cls.objects.get(email=email, role__in=[Roles.PARTICIPANT.value]) except db.DoesNotExist: user = None return user @classmethod def find_all_coaches(cls) -> QuerySet: return cls.objects( role__in=[Roles.ADMIN.value, Roles.COACH.value]).all() def add_participant_role(self) -> None: """ To use when we want to update the role of the user to participant. Init data specific to the participant :return: """ self.role.append(Roles.PARTICIPANT.value) self.workshopParticipations = [] return
class Column(Base): meta = { 'increase_key': False, 'collection': 'column', 'ordering': ['-created_at'], 'strict': True, 'id_field': '_id' } _id = db.StringField() title = db.StringField(max_length=30) # 标题 sub_title = db.StringField(max_length=30) # 副标题 description = db.StringField() # 简述 target = db.StringField(max_length=1000) # 标记,用于链接跳转或其它 column_zone_id = db.StringField(default='') # 空间ID user_id = db.IntField(default=0) sort = db.IntField(default=0) # 排序 kind = db.IntField(default=1) # 类型:1.--;2.--;3.-- cover_id = db.StringField(default='') # 封面ID status = db.IntField(default=0) # 是否发布:0.否;1.是; deleted = db.IntField(default=0) remark = db.StringField() # 备注 created_at = db.DateTimeField() updated_at = db.DateTimeField(default=datetime.datetime.now) # 封面 def cover(self): if self.cover_id and len(self.cover_id) == 24: asset = Asset.objects(_id=ObjectId(self.cover_id)).first() if asset and asset.deleted == 0: return asset asset = Asset.objects(target_id=str(self._id), asset_type=7, deleted=0).first() if asset and asset.deleted == 0: return asset return None # 标记删除 def mark_delete(self): ok = super(Column, self).update(deleted=1) if ok: # 删除附件 assets = Asset.objects(target_id=str(self._id), asset_type=7, deleted=0) for item in assets: item.mark_delete() # 标记恢复 def mark_recovery(self): ok = super(Column, self).update(deleted=0) if ok: # 恢复附件 assets = Asset.objects(target_id=str(self._id), asset_type=7, deleted=1) for item in assets: item.update(deleted=0) def __unicode__(self): return self.title
class Category(Base): meta = { 'increase_key': True, 'collection': 'category', 'ordering': ['-created_at'], 'strict': True, 'id_field': '_id' } _id = db.IntField(primary_key=True, required=True) mark = db.StringField(max_length=20) name = db.StringField(max_length=30, required=True, unique=True) user_id = db.IntField(required=True) kind = db.IntField(default=1) # 类型:1.文档;2.素材;3.-- pid = db.IntField(default=0) cid = db.IntField(default=0) sort = db.IntField(default=0) # 排序 status = db.IntField(default=0) deleted = db.IntField(default=0) remark = db.StringField() created_at = db.DateTimeField() updated_at = db.DateTimeField(default=datetime.datetime.now) def mark_delete(self): return super(Category, self).update(deleted=1) def __unicode__(self): return self.name @classmethod def category_kind_options(self, kind=0): data = [{ 'id': 1, 'name': '文档' }, { 'id': 2, 'name': '素材' }, { 'id': 3, 'name': '未定义2' }] if kind == 0: return data else: for d in data: if d['id'] == kind: return d return {'id': 0, 'name': ''} # 获取父级 @classmethod def fetch_parent_options(self, kind=0): query = {} if kind != 0: query['kind'] = int(kind) query['pid'] = 0 data = Category.objects( **query).order_by('-created_at').order_by('-sort').limit(50) # 过滤数据 for i, d in enumerate(data): kind_label = '--' if d.kind == 1: kind_label = '文档' if d.kind == 2: kind_label = '备用' data[i].kind_label = kind_label return data def list(self, kind=0, **kwargs): query = {} if kind != 0: query['kind'] = int(kind) catetories = Category.objects(**query) return catetories
class Sequence(db.Document): name = db.StringField(max_length=10, required=True, unique=True) val = db.IntField()