class PeeweePartialMixin(PartialMixin, BaseModel): token = CharField() # base64 encoded data = JSONField(null=True) next_step = IntegerField() backend = CharField() @classmethod def load(cls, token): try: return cls.get(cls.token == token) except cls.DoesNotExist: return None @classmethod def destroy(cls, token): partial = cls.load(token) if partial: partial.delete()
class PeeweeUserMixin(UserMixin, BaseModel): provider = CharField() extra_data = JSONField(null=True) uid = CharField() user = None @classmethod def changed(cls, user): user.save() def set_extra_data(self, extra_data=None): if super(PeeweeUserMixin, self).set_extra_data(extra_data): self.save() @classmethod def username_max_length(cls): username_field = cls.username_field() field = getattr(cls.user_model(), username_field) return field.max_length @classmethod def username_field(cls): return getattr(cls.user_model(), 'USERNAME_FIELD', 'username') @classmethod def allowed_to_disconnect(cls, user, backend_name, association_id=None): if association_id is not None: query = cls.select().where(cls.id != association_id) else: query = cls.select().where(cls.provider != backend_name) query = query.where(cls.user == user) if hasattr(user, 'has_usable_password'): valid_password = user.has_usable_password() else: valid_password = True return valid_password or query.count() > 0 @classmethod def disconnect(cls, entry): entry.delete_instance() @classmethod def user_exists(cls, *args, **kwargs): """ Return True/False if a User instance exists with the given arguments. """ user_model = cls.user_model() query = get_query_by_dict_param(user_model, kwargs) return user_model.select().where(query).count() > 0 @classmethod def get_username(cls, user): return getattr(user, cls.username_field(), None) @classmethod def create_user(cls, *args, **kwargs): username_field = cls.username_field() if 'username' in kwargs and username_field not in kwargs: kwargs[username_field] = kwargs.pop('username') return cls.user_model().create(*args, **kwargs) @classmethod def get_user(cls, pk, **kwargs): if pk: kwargs = {'id': pk} try: return cls.user_model().get( get_query_by_dict_param(cls.user_model(), kwargs)) except cls.user_model().DoesNotExist: return None @classmethod def get_users_by_email(cls, email): user_model = cls.user_model() return user_model.select().where(user_model.email == email) @classmethod def get_social_auth(cls, provider, uid): if not isinstance(uid, six.string_types): uid = str(uid) try: return cls.select().where(cls.provider == provider, cls.uid == uid).get() except cls.DoesNotExist: return None @classmethod def get_social_auth_for_user(cls, user, provider=None, id=None): query = cls.select().where(cls.user == user) if provider: query = query.where(cls.provider == provider) if id: query = query.where(cls.id == id) return list(query) @classmethod def create_social_auth(cls, user, uid, provider): if not isinstance(uid, six.string_types): uid = str(uid) return cls.create(user=user, uid=uid, provider=provider)
class PackageVersion(Model): package = p.ForeignKeyField(Package, index=True, null=False) version = VersionField(index=True, null=False) hidden = p.BooleanField(default=False, null=False, index=True) downloads = p.IntegerField(default=0, index=True) author = p.CharField(max_length=255, null=True) author_email = p.CharField(max_length=255, null=True) maintainer = p.CharField(max_length=255, null=True) maintainer_email = p.CharField(max_length=255, null=True) home_page = p.CharField(max_length=256, null=True) license = p.TextField(null=True) summary = p.CharField(max_length=255, null=True) description = p.TextField(null=True) keywords = JSONField(default=[]) platform = p.CharField(max_length=255, null=True) download_url = p.CharField(max_length=255, null=True) classifiers = JSONField(default=[]) requires = JSONField(default=[]) requires_dist = JSONField(default=[]) provides = JSONField(default=[]) provides_dist = JSONField(default=[]) requires_external = JSONField(default=[]) requires_python = p.CharField(max_length=255, null=True) obsoletes = JSONField(default=[]) obsoletes_dist = JSONField(default=[]) project_url = p.CharField(max_length=255, null=True) def __hash__(self): return hash((self.package_id, self.version)) def __eq__(self, other): return hash(self) == hash(other) def __gt__(self, other): assert isinstance(other, PackageVersion) a = () a += (self.package_id, ) a += self.version.version b = () b += (other.package_id, ) b += other.version.version return a > b @timeit def files(self): return PackageFile.select().where(PackageFile.package == self.package, PackageFile.version == self) @timeit def find_file(self, name): return PackageFile.select().where(PackageFile.basename == name) @timeit def create_file(self, name): name = os.path.basename(name) if PackageFile.select().where(PackageFile.basename == name).count(): raise p.DataError("Duplicate file") pkg_file = PackageFile(package=self.package, version=self, basename=name, file=os.path.join(PackageFile.file.STORAGE, self.package.name, str(self.version), name)) pkg_file.save() return pkg_file @timeit def update_metadata(self, metadata): print(metadata) def __str__(self): return "%s" % self.version
class User(peewee.Model, ModelMixin): """setting = { page } """ id = peewee.PrimaryKeyField() username = peewee.CharField(max_length=20, index=True) password = peewee.CharField(max_length=256) salt = peewee.CharField(max_length=20) config = JSONField() created_at = peewee.DateTimeField(default=datetime.utcnow) class Meta: database = db db_table = "user" @classmethod def get_config(cls): user = cls.select().first() return user.config if user and user.config else None def validate(self, password): hashed_password, salt = self.generate_salt_and_hash_password(password, self.salt) return hashed_password == self.password @classmethod def generate_salt_and_hash_password(cls, password, salt=None): salt = salt or str(time.time())[:20] password = hashlib.sha512(password.encode("utf-8")).hexdigest() password = hashlib.sha512(password.encode("utf-8") + salt.encode("utf-8")).hexdigest() return password, salt @classmethod def create_user(cls, username, password): users = cls.get_list(User.username == username) if users: raise Exception("{} already exists, please choose another".format(username)) # generate_password password, salt = cls.generate_salt_and_hash_password(password) user = cls( username=username, password=password, salt=salt ) user.save() @classmethod def delete_user(cls, username): user = cls.get_one(User.username == username) user.delete_instance() @classmethod def get_sidebar(cls): """ generate sidebar if it does not exist or it has expired """ if not hasattr(cls, "sidebar"): cls.generate_sidebar() sidebar = getattr(cls, "sidebar") if sidebar["expired_at"] <= time.time(): sidebar = cls.generate_sidebar() return sidebar["data"] @classmethod def update_sidebar(cls, *args, **kwargs): """ subscribe to a signal and update sidebar when needed """ cls.generate_sidebar() @classmethod def generate_sidebar(cls): """ User.sidebar = { "exipred_at": timestamp, "data": {} } """ config = cls.get_config() or current_app.config rr = { "tags": None, "comments": None, "links": None, "announce": None, "announce_length": 0 } tags = Tag.select( Tag.name, fn.COUNT(Tag.name).alias("count") ).group_by(Tag.name).order_by(-fn.COUNT(Tag.name)).limit(config["TAG_COUNT"]) rr["tags"] = tags comments = Comment.get_list().\ order_by(Comment.id.desc()).limit(config["COMMENT_COUNT"]) rr["comments"] = comments links = Link.get_list( Link.display == True ).order_by(Link.id.desc()).limit(config["LINK_COUNT"]) rr["links"] = links announce = Post.get_one(Post.id == config["ANNOUNCE_ID"]) rr["announce"] = announce rr["announce_length"] = config["ANNOUNCE_LENGTH"] cls.sidebar = { "data": rr, "expired_at": time.time() + 8 * 60 * 60 } return cls.sidebar