예제 #1
0
class Message(Model, Base):
    class Meta:
        table = "message"

    db_fields = [
        'id', 'created', 'modified', 'client_id', 'uid', 'type', 'state', 'data'
    ]

    db_field_datetime = [
        'created', 'modified'
    ]
    db_field_enum = [
        'type'
    ]

    id = fields.BigIntField(pk=True)
    created = fields.DatetimeField(auto_now_add=True)
    modified = fields.DatetimeField(auto_now=True)

    client_id = fields.BigIntField(null=True, default=None)
    uid = fields.CharField(max_length=64, index=True, default=None)
    type = fields.CharEnumField(enum_type=MessageType, null=True, default=None)
    state = fields.CharEnumField(enum_type=MessageState, null=True, default=None)
    _data = fields.TextField(source_field='data')

    @property
    def data(self) -> dict:
        return json.loads(self._data) if self._data else {}

    @data.setter
    def data(self, data: dict):
        self._data = json.dumps(data, cls=DefaultJSONEncoder)
예제 #2
0
class Issue(models.Model):

    issue_uuid = fields.UUIDField(unique=True, default=uuid.uuid4)

    title = fields.CharField(max_length=255)

    description = fields.TextField()

    customer = fields.ForeignKeyField(
        "models.User", related_name="issues", on_delete=fields.CASCADE
    )

    city = fields.CharEnumField(enum_type=City, max_length=400)

    sub_city = fields.CharEnumField(enum_type=SubCity, max_length=200)

    time_to_come_from = fields.DatetimeField()

    time_to_come_to = fields.DatetimeField()

    amount_from = fields.IntField(null=True)

    amount_to = fields.IntField(null=True)

    is_negotiable = fields.BooleanField(default=False)

    is_open = fields.BooleanField(default=True)

    created_at = fields.DatetimeField(auto_now_add=True)

    def __str__(self) -> str:
        return f"{self.title}"
예제 #3
0
파일: game.py 프로젝트: lekha/jeopardy
class GameOrm(BaseOrmModel):
    name = fields.CharField(255)
    code = fields.CharField(4, unique=True)
    owner = fields.ForeignKeyField("models.UserOrm", related_name="games")
    max_teams = fields.IntField()
    max_players_per_team = fields.IntField()
    status = fields.CharEnumField(GameStatus, default=GameStatus.EDITABLE)
    next_message_id = fields.BigIntField(null=True)
    next_round = fields.ForeignKeyField(
        "models.RoundOrm",
        related_name=None,
        on_delete="RESTRICT",
        null=True,
    )
    next_action_type = fields.CharEnumField(ActionType, null=True)
    next_chooser = fields.ForeignKeyField(
        "models.TeamOrm",
        related_name=None,
        on_delete="RESTRICT",
        null=True,
    )

    class Meta:
        table = "games"

    def __str__(self):
        return f"Game({self.id}, {self.code}, {self.name})"
예제 #4
0
class DBUser(Model):
    dc_id = fields.BigIntField(pk=True)
    dc_nick = fields.TextField()
    ubisoft_id = fields.TextField()
    uplay_id = fields.TextField()
    r6_nick = fields.TextField()
    kd = fields.FloatField()
    level = fields.IntField(null=True)
    mmr = fields.IntField()
    rank = fields.TextField()
    rank_short = fields.CharEnumField(RankShort)
    last_update = fields.DatetimeField()
    last_command = fields.DatetimeField()
    last_change = fields.DatetimeField()
    platform = fields.CharEnumField(Platform)
#    banned = fields.BooleanField()
    inactive = fields.BooleanField()

    def update_from_player(self, player: Player, is_from_command: bool):
        if is_from_command:
            self.last_command = datetime.today()
            self.inactive = False
        if (self.mmr != player.mmr) or (self.rank != player.rank):
            self.last_change = datetime.today()
            self.inactive = False
        self.ubisoft_id = player.ubisoft_id
        self.uplay_id = player.uplay_id
        self.kd = player.kd
        self.level = player.level
        self.mmr = player.mmr
        self.rank = player.rank
        self.rank_short = player.rank_short
        self.last_update = datetime.today()

    @staticmethod
    def create_from_player(ctx: Context, player: Player) -> 'DBUser':
        db_user = DBUser(
            dc_id=ctx.author.id,
            dc_nick=ctx.author.name,
            ubisoft_id=player.ubisoft_id,
            uplay_id=player.uplay_id,
            r6_nick=player.name,
            kd=player.kd,
            level=player.level,
            mmr=player.mmr,
            rank=player.rank,
            rank_short=player.rank_short,
            last_update=datetime.today(),
            last_command=datetime.today(),
            last_change=datetime.today(),
            platform=player.platform,
            inactive=False
        )
        return db_user
예제 #5
0
class Interface(AbstractModel):
    desc = fields.TextField(description="描述信息", null=True)
    path = fields.CharField(255, description="接口路径", null=True, default="")
    standard = fields.CharEnumField(Standard,
                                    description="使用规范",
                                    default=Standard.RESTFUL)
    method = fields.CharEnumField(Methods,
                                  description="请求方法",
                                  default=Methods.GET)
    project = fields.ForeignKeyField('models.Project',
                                     related_name='Interfaces')

    class PydanticMeta:
        max_recursion = 2
class Content(Model):
    id = fields.IntField(pk=True, required=False)
    type = fields.CharEnumField(ContentType,
                                description='Either ``"Show"`` or ``"Movie"``',
                                default=ContentType.MOVIE)
    title = fields.CharField(max_length=400, required=False)
    date_added = fields.DateField(auto_now=False,
                                  auto_now_add=False,
                                  default=datetime.date.today())
    release_year = fields.IntField(null=True)
    rating = fields.CharEnumField(Rating,
                                  description="TV or MPAA Rating",
                                  default=Rating.NR)
    duration = fields.IntField(required=False)
    description = fields.TextField(null=True)
예제 #7
0
class Package(Model):
    id = fields.BigIntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_add=True, null=True)
    name = fields.CharField(max_length=255)
    responsible_username = fields.CharField(max_length=255)
    is_module = fields.BooleanField(default=False)
    is_package = fields.BooleanField(default=False)
    is_published = fields.BooleanField(default=False)
    part_of_module = fields.BooleanField(default=False)
    signed = fields.BooleanField(default=False)
    last_import = fields.DatetimeField(null=True)
    last_build = fields.DatetimeField(null=True)

    el8 = fields.BooleanField(default=False)
    el9 = fields.BooleanField(default=False)
    repo = fields.CharEnumField(Repo, null=True)

    builds: Optional[fields.ReverseRelation[Build]]
    imports: Optional[fields.ReverseRelation[Import]]

    class Meta:
        table = "packages"

    class PydanticMeta:
        exclude = ("m_module_parent_packages", "m_subpackages")
예제 #8
0
class Task(Model):
    author = fields.ForeignKeyField('models.User',
                                    related_name='tasks',
                                    on_delete='CASCADE')
    game = fields.ForeignKeyField(
        'models.Game',
        on_delete='CASCADE',
    )
    content = fields.TextField()
    complexity = fields.CharEnumField(
        enum_type=ComplexityTypes,
        max_length=100,
        null=True,
    )

    class Meta:
        ordering = [
            '-id',
        ]

    def __str__(self):
        return f'Task-{self.id}'

    async def vote_distribution(self):
        grouped_complexity = await (self.votes.all().annotate(
            count=Count('id')).group_by('complexity').values(
                'complexity', 'count'))
        return {
            compl['complexity']: compl['count']
            for compl in grouped_complexity
        }
예제 #9
0
파일: user.py 프로젝트: lekha/jeopardy
class UserOrm(BaseOrmModel):
    username = fields.CharField(255)
    is_active = fields.BooleanField(default=1)
    auth_provider = fields.CharEnumField(AuthProvider)
    anonymous_metadata = fields.ForeignKeyField(
        "models.AnonymousUserMetadataOrm",
        related_name="user",
        on_delete="RESTRICT",
        null=True,
    )
    google_metadata = fields.ForeignKeyField(
        "models.GoogleUserMetadataOrm",
        related_name="user",
        on_delete="RESTRICT",
        null=True,
    )

    class Meta:
        table = "users"

    def __str__(self):
        return f"User({self.id}, {self.username})"

    async def team(self, game: GameOrm) -> TeamOrm:
        """Find the team a user is on for the game if they are on one."""
        _team = (await
                 TeamOrm.filter(game=game).filter(players__id=self.id).first())
        return _team
예제 #10
0
파일: users.py 프로젝트: revensky/psion
class User(Model, UserMixin):
    id = fields.UUIDField(pk=True)
    password = fields.CharField(80)
    given_name = fields.CharField(24)
    middle_name = fields.CharField(64, null=True)
    family_name = fields.CharField(64)
    nickname = fields.CharField(16, null=True)
    preferred_username = fields.CharField(16, null=True)
    profile = fields.CharField(128, null=True)
    picture = fields.CharField(256, null=True)
    website = fields.CharField(128, null=True)
    email = fields.CharField(64)
    email_verified = fields.BooleanField(default=False)
    gender = fields.CharEnumField(Genders, max_length=6, null=True)
    birthdate = fields.DateField(null=True)
    zoneinfo = fields.CharField(32, null=True)
    locale = fields.CharField(16, null=True)
    phone_number = fields.CharField(32, null=True)
    phone_number_verified = fields.BooleanField(default=False)
    address = fields.JSONField(null=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)

    class Meta:
        table = "users"

    def get_user_id(self) -> str:
        return str(self.id)
예제 #11
0
class Event(Model, state_machine.StateMachineMixin):
    STATE_ENUM = StateEnum
    ALIAS = state_alias

    name = fields.CharField(max_length=255, index=True)
    description = fields.TextField(null=True)
    categories = fields.ManyToManyField("models.Category",
                                        related_name="events",
                                        through="event_category")

    address = fields.CharField(max_length=500, null=True)
    longitude = fields.FloatField(null=True)
    latitude = fields.FloatField(null=True)

    start = fields.DatetimeField()
    end = fields.DatetimeField()

    user = fields.ForeignKeyField("models.User", related_name="user_events")
    followers = fields.ManyToManyField("models.User",
                                       related_name="follow_events",
                                       through="event_follow")

    state = fields.CharEnumField(StateEnum, max_length=40)

    def __str__(self):
        return self.name

    class Meta:
        table = "party_maker_events"
예제 #12
0
class Client(Model, Base):
    class Meta:
        table = "client"

    db_fields = [
        'created', 'modified', 'remote_id', 'uid', 'connection', 'connection_change', 'ip'
    ]

    db_field_datetime = [
        'created', 'modified', 'connection_change'
    ]
    db_field_enum = [
        'connection'
    ]

    id = fields.BigIntField(pk=True)
    created = fields.DatetimeField(auto_now_add=True)
    modified = fields.DatetimeField(auto_now=True)

    access_id = fields.BigIntField(null=True, default=None)
    remote_id = fields.BigIntField(null=True, default=None)
    uid = fields.CharField(max_length=64, index=True, default=None)
    basicauth_password = fields.CharField(max_length=64, null=True, default=None)
    ip = fields.CharField(max_length=64, null=True, default=None)
    connection = fields.CharEnumField(enum_type=Connection, null=True, default=None)
    connection_change = fields.DatetimeField(null=True, default=None)
예제 #13
0
class AppBaseModel(models.Model):
    id = fields.IntField(pk=True)
    status = fields.CharEnumField(Status, default=Status.ACTIVE)
    created_at = fields.DatetimeField(null=True, auto_now_add=True)
    modified_at = fields.DatetimeField(null=True, auto_now=True)
    """ Database methods """
    @classmethod
    async def create_one(cls, item):
        return await cls.create(**item.dict())

    @classmethod
    async def find_by(cls, **kwargs):
        return await cls.filter(**kwargs).all()

    @classmethod
    async def find_one(cls, **kwargs):
        return await cls.filter(**kwargs).first()

    @classmethod
    async def update_one(cls, _id: int, item):
        await cls.filter(id=_id).update(**item.dict(exclude_unset=True))
        return cls.get(id=_id)

    @classmethod
    async def delete_one(cls, _id: int) -> int:
        deleted_count = await cls.filter(id=_id).delete()
        return deleted_count

    class Meta:
        __abstract__ = True
예제 #14
0
class Import(Model):
    id = fields.BigIntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_add=True, null=True)
    package = fields.ForeignKeyField("distrobuild.Package",
                                     on_delete="RESTRICT",
                                     related_name="imports")
    status = fields.CharEnumField(ImportStatus)
    module = fields.BooleanField(default=False)
    version = fields.IntField()
    executor_username = fields.CharField(max_length=255)

    commits: fields.ManyToManyRelation[
        "ImportCommit"] = fields.ManyToManyField("distrobuild.ImportCommit",
                                                 related_name="imports",
                                                 forward_key="id",
                                                 backward_key="import__id",
                                                 through="import_commits")

    class Meta:
        table = "imports"
        ordering = ["-created_at"]

    class PydanticMeta:
        exclude = ("batch_imports", )
예제 #15
0
class Build(Model):
    id = fields.BigIntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_add=True, null=True)
    package = fields.ForeignKeyField("distrobuild.Package",
                                     on_delete="RESTRICT",
                                     related_name="builds")
    status = fields.CharEnumField(BuildStatus)
    mbs = fields.BooleanField(default=False)
    signed = fields.BooleanField(default=False)
    scratch = fields.BooleanField(default=False)
    scratch_merged = fields.BooleanField(default=False)
    koji_id = fields.BigIntField(null=True)
    mbs_id = fields.BigIntField(null=True)
    import_commit = fields.ForeignKeyField("distrobuild.ImportCommit",
                                           on_delete="RESTRICT",
                                           related_name="builds")
    executor_username = fields.CharField(max_length=255)
    force_tag = fields.CharField(max_length=255, null=True)
    arch_override = fields.TextField(null=True)
    exclude_compose = fields.BooleanField(default=False)
    point_release = fields.CharField(max_length=255)

    class Meta:
        table = "builds"
        ordering = ["-created_at"]

    class PydanticMeta:
        exclude = ("batch_builds", )
예제 #16
0
class ScheduledVisit(models.Model):
    date = fields.DateField(auto_now_add=True)
    lesson: Lesson = fields.ForeignKeyField('lesson_schedule.Lesson', on_delete=fields.CASCADE)
    image: Optional[Path] = ImageField(upload_to='visit/', null=True)
    status = fields.CharEnumField(enums.VisitStatuses, default=enums.VisitStatuses.CREATED)
    error_message = fields.CharField(max_length=512, null=True)
    visit_start = fields.DatetimeField(null=True)
    visit_finish = fields.DatetimeField(null=True)

    # Relations
    owner: 'auth.User' = fields.ForeignKeyField(
        model_name='auth.User',
        related_name='visits',
        on_delete=fields.CASCADE,
    )

    async def delete(self, using_db: Optional[BaseDBAsyncClient] = None) -> None:
        self._delete_img()
        return await super().delete(using_db)

    def set_image(self, image: Union[io.IOBase, Path, bytes]):

        if isinstance(image, bytes):
            buffer = io.BytesIO()
            buffer.name = f'{uuid.uuid4()}.png'
            buffer.write(image)
            image = buffer

        self._delete_img()
        self.image = image

    def _delete_img(self):
        if self.image:
            storage = ImageStorage.from_path(self.image)
            storage.delete(self.image.name)
예제 #17
0
파일: models.py 프로젝트: poeticloud/eva
class IdP(TimestampModelMixin, models.Model):
    """IdP
    第三方身份认证,如: - LDAP - Google - Github - WeChat
    其他如x509证书 cn 标识鉴别
    """

    @enum.unique
    class Type(enum.Enum):
        LDAP = "LDAP"
        OIDC = "OIDC"
        GOOGLE = "GOOGLE"
        FACEBOOK = "FACEBOOK"
        TWITTER = "TWITTER"
        GITHUB = "GITHUB"
        GITLAB = "GITLAB"
        WECHAT = "WECHAT"
        WEIBO = "WEIBO"

    id = fields.BigIntField(pk=True)
    name = fields.CharField(max_length=32)
    type = fields.CharEnumField(Type, description="IdP类型")

    config = fields.JSONField(null=True, description="该IdP的详细配置")
    is_active = fields.BooleanField(default=False, description="该IdP是否启用?")

    class Meta:
        table = "eva_idp"
예제 #18
0
class Case(AbstractModel):
    name = fields.CharField(max_length=255, description="用例名称", unique=True)
    token = fields.BooleanField(default=False, description="token读写操作,默认为读")
    token_path = fields.CharField(max_length=255,
                                  description="jsonpath提取token表达式",
                                  null=True,
                                  default=None)
    content_type = fields.CharEnumField(ContentType,
                                        description="参数类型",
                                        default=ContentType.PARAMS)
    # graphql 规范的请求体
    query = fields.TextField(description="graphql query语句",
                             null=True,
                             default=None)
    # 请求参数
    body = fields.TextField(description="请求参数",
                            null=True,
                            allow_none=True,
                            default=None)
    extra = fields.CharField(255,
                             description="从接口响应提取参数",
                             null=True,
                             allow_none=True,
                             default=None)
    expect = fields.TextField(description="预期结果", default='{}')
    interface = fields.ForeignKeyField('models.Interface',
                                       related_name='Cases',
                                       description="所属接口")

    class PydanticMeta:
        max_recursion = 2
예제 #19
0
파일: reveals.py 프로젝트: lekha/jeopardy
class RoundRevealOrm(BaseOrmModel):
    round_ = fields.ForeignKeyField(
        "models.RoundOrm",
        source_field="round_id",
        related_name="reveals",
        on_delete="CASCADE",
    )
    level = fields.CharEnumField(BoardLevel)
    level_id = fields.BigIntField()
    detail = fields.CharEnumField(BoardLevelDetail)

    class Meta:
        table = "round_reveals"
        unique_together = (("round_", "level", "level_id", "detail"))

    def __str__(self):
        return f"RoundReveal({self.id}, {self.level}, self.level_id)"
예제 #20
0
class VoiceChannels(models.Model):
    class Meta:
        table = "voice_channels"

    id = fields.BigIntField(pk=True)
    owner_id = fields.BigIntField()
    sequence = fields.IntField(default=0)
    channel_id = fields.BigIntField()
    type = fields.CharEnumField(VoiceType, default=VoiceType.normal)
예제 #21
0
class HealthStatusMixin:
    health_status = fields.CharEnumField(HealthStatus, max_length=255, null=True)
    health_message = fields.TextField(null=True)

    def to_dict(self):
        return {
            "health_status": self.health_status.value,  # false positive, pylint: disable=no-member
            "health_message": self.health_message,
        }
예제 #22
0
class QueryString(Model):
    """This is the database model capturing the user submitted queries."""
    id = fields.IntField(pk=True)
    query = fields.CharField(max_length=1024)
    language = fields.CharEnumField(max_length=0, enum_type=Language)
    results = fields.JSONField(null=True)
    created = fields.DatetimeField(auto_now_add=True)

    def __str__(self) -> str:
        return self.query
예제 #23
0
class State(Model):
    """Stores current level of index and hash of it's config"""

    index_name = fields.CharField(256)
    index_type = fields.CharEnumField(IndexType)
    hash = fields.CharField(256)
    level = fields.IntField(default=0)

    class Meta:
        table = 'dipdup_state'
예제 #24
0
class VoiceConfig(models.Model):
    class Meta:
        table = "voice_config"

    id = fields.BigIntField(pk=True)
    guild_id = fields.BigIntField()
    channel_id = fields.BigIntField()
    name = fields.CharField(max_length=100, null=True)
    limit = fields.IntField(default=0)
    type = fields.CharEnumField(VoiceType, default=VoiceType.normal)
예제 #25
0
class User(models.Model):

    user_uuid = fields.UUIDField(unique=True, default=uuid.uuid4)

    username = fields.CharField(max_length=250, unique=True)

    email = fields.CharField(unique=True, max_length=400)

    password = fields.CharField(max_length=512)

    full_name = fields.TextField()

    phone_number = fields.CharField(max_length=10, unique=True)

    is_superuser = fields.BooleanField(default=False)

    is_staff = fields.BooleanField(
        default=False,
        description="Designates whether the user can log into this admin site.",
    )

    is_active = fields.BooleanField(
        default=True,
        description=""""Designates whether this user should be treated as active.
            Unselect this instead of deleting accounts.""",
    )

    career = fields.CharEnumField(enum_type=Career, max_length=200, null=True)

    is_worker = fields.BooleanField(
        default=False,
        description="Designates whether the user is worker.",
        null=True)

    is_customer = fields.BooleanField(
        default=False,
        description="Designates whether the user is customer.",
        null=True)

    date_joined = fields.DatetimeField(auto_now_add=True)

    def __str__(self) -> str:
        return f"{self.username}"

    class PydanticMeta:

        exclude = (
            "password",
            "id",
            "date_joined",
            "user_uuid",
            "is_superuser",
            "is_staff",
            "is_active",
        )
예제 #26
0
class Episode(Model):
    name = fields.CharEnumField(Shows)
    show = fields.ForeignKeyField('models.Show',
                                  related_name='episodes',
                                  on_delete=fields.RESTRICT)
    synopsis = fields.TextField()
    link = fields.CharField(max_length=255)
    air_date = fields.DatetimeField()

    def __str__(self):
        return self.name
예제 #27
0
class Transaction(Model):
    id = fields.UUIDField(pk=True)
    amount = fields.DecimalField(max_digits=19, decimal_places=4)
    description = fields.TextField(null=True)
    status: TransactionStatus = fields.CharEnumField(
        TransactionStatus, default=TransactionStatus.PENDING
    )
    error = fields.TextField(null=True)
    created_at = fields.DatetimeField(auto_now_add=True)

    class Meta:
        abstract = True
예제 #28
0
class Job(Model):
    task = fields.CharField(max_length=200)
    args = fields.JSONField(null=True)
    kwargs = fields.JSONField(null=True)
    job_retry = fields.IntField()
    job_retries = fields.IntField(default=0)
    job_retry_after = fields.IntField()
    job_id = fields.CharField(max_length=200, unique=True)
    enqueue_time = fields.DatetimeField()
    expire_time = fields.DatetimeField(null=True)
    status = fields.CharEnumField(job.JobStatus)

    class Meta:
        ordering = ['-id']
예제 #29
0
class Course(models.Model):
    """The course model."""

    id = fields.UUIDField(pk=True)

    title = fields.CharField(max_length=100)

    overview = fields.TextField()

    cover = fields.CharField(null=True, max_length=500)

    video = fields.CharField(null=True, max_length=500)

    categories = fields.ManyToManyField("models.Category",
                                        related_name="courses")

    languages = fields.ManyToManyField("models.Language",
                                       related_name="courses")

    level = fields.CharEnumField(enum_type=Level, max_length=100)

    teacher = fields.ForeignKeyField(
        model_name="models.Teacher",
        related_name="courses",
        on_delete=fields.SET_NULL,
        null=True,
    )

    price = fields.FloatField(default=0)

    discount = fields.FloatField(default=0)

    is_drift = fields.BooleanField(default=True)

    is_active = fields.BooleanField(default=True)

    slug = fields.CharField(unique=True, max_length=200)

    created_at = fields.DatetimeField(auto_now_add=True)

    updated_at = fields.DatetimeField(auto_now=True)

    class Meta:
        """Meta data."""

        table = "course"

    def __str__(self: "Course") -> str:
        """The string representative for course class."""
        return f"{self.title}"
예제 #30
0
파일: db.py 프로젝트: ndawn/echo
class Device(Model):
    subnet = fields.ForeignKeyField(
        model_name='models.Subnet',
        related_name='devices',
        null=True,
        on_delete=fields.RESTRICT,
    )
    hostname = fields.CharField(max_length=255, default='')
    address = fields.CharField(max_length=15, unique=True)
    mac = fields.CharField(max_length=17, null=True)
    name = fields.CharField(max_length=64, default='')
    type = fields.CharEnumField(enum_type=DeviceTypeEnum)
    connection_options = fields.JSONField(encoder=ujson.dumps, decoder=ujson.loads)
    connected_with = fields.JSONField(encoder=ujson.dumps, decoder=ujson.loads)