How to use the peewee.DateTimeField function in peewee

To help you get started, we’ve selected a few peewee examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github anqxyr / jarvis / jarvis / db.py View on Github external
db = SqliteExtDatabase('jarvis.db', journal_mode='WAL')


class BaseModel(peewee.Model):

    class Meta:
        database = db


class Tell(BaseModel):
    sender = peewee.CharField()
    recipient = peewee.CharField(index=True)
    topic = peewee.CharField(null=True)
    text = peewee.TextField()
    time = peewee.DateTimeField()


class Message(BaseModel):
    user = peewee.CharField(index=True)
    channel = peewee.CharField()
    time = peewee.CharField()
    text = peewee.TextField()


class Quote(BaseModel):
    user = peewee.CharField(index=True)
    channel = peewee.CharField()
    time = peewee.CharField()
    text = peewee.TextField()
github AXErunners / sentinel / lib / models.py View on Github external
if signal:
            query = query.where(Vote.signal == signal)

        if outcome:
            query = query.where(Vote.outcome == outcome)

        count = query.count()
        return count


class Setting(BaseModel):
    name = CharField(default='')
    value = CharField(default='')
    created_at = DateTimeField(default=datetime.datetime.utcnow())
    updated_at = DateTimeField(default=datetime.datetime.utcnow())

    class Meta:
        db_table = 'settings'


class Proposal(GovernanceClass, BaseModel):
    governance_object = ForeignKeyField(GovernanceObject, related_name='proposals', on_delete='CASCADE', on_update='CASCADE')
    name = CharField(default='', max_length=40)
    url = CharField(default='')
    start_epoch = IntegerField()
    end_epoch = IntegerField()
    payment_address = CharField(max_length=36)
    payment_amount = DecimalField(max_digits=16, decimal_places=8)
    object_hash = CharField(max_length=64)

    # src/governance-validators.cpp
github vilmibm / tildemush / server / tmserver / models.py View on Github external
class BaseModel(Model):
    created_at = pw.DateTimeField(default=datetime.utcnow)
    class Meta:
        database = config.get_db()

class UserAccount(BaseModel):
    """This model represents the bridge between the game world (a big tree of
    objects) and a live conncetion from a game client. A user account doesn't
    "exist," per se, in the game world, but rather is anchored to a single
    "player" object. this player object is the useraccount's window on the game
    world."""

    username = pw.CharField(unique=True)
    password = pw.CharField()
    updated_at = pw.DateTimeField(null=True)
    is_god = pw.BooleanField(default=False)

    def _hash_password(self):
        self.password = bcrypt.hashpw(self.password.encode('utf-8'), bcrypt.gensalt())

    def check_password(self, plaintext_password):
        pw = self.password
        if type(self.password) == type(''):
            pw = self.password.encode('utf-8')
        return bcrypt.checkpw(plaintext_password.encode('utf-8'), pw)

    def validate(self):
        if 0 != len(UserAccount.select().where(UserAccount.username == self.username)):
            raise UserValidationError('username taken: {}'.format(self.username))

        if BAD_USERNAME_CHARS_RE.search(self.username):
github harvard / cloudJHub / jupyterhub_files / models.py View on Github external
# Replace:
#   DB_NAME with the database name in MySQL database 
#   DB_HOST the DNS or the IP of the MySQL host
#   DB_USERNAME and DB_USERPASSWORD with username and password of a privileged user.
# Example : 
#    DB = MySQLDatabase('jupyterhub_model', host = "54.0.0.99" , user='jupyterhub_user', passwd="Jupyter#ub_!")


class BaseModel(Model):
    class Meta:
        database = DB


class Server(BaseModel):
    server_id = CharField(unique=True)
    created_at = DateTimeField(default=datetime.datetime.now)
    user_id = CharField(unique=True)
    # ebs_volume_id = TextField(unique=True)

    @classmethod
    def new_server(cls, server_id, user_id):
        cls.create(server_id=server_id, user_id=user_id)

    @classmethod
    def get_server(cls, user_id):
        return cls.get(user_id=user_id)

    @classmethod
    def get_server_count(cls):
        return cls.select().count()

    @classmethod
github RRoodselaar / PokeVision / pogom / models.py View on Github external
class Gym(BaseModel):
    UNCONTESTED = 0
    TEAM_MYSTIC = 1
    TEAM_VALOR = 2
    TEAM_INSTINCT = 3

    gym_id = CharField(primary_key=True)
    team_id = IntegerField()
    guard_pokemon_id = IntegerField()
    gym_points = IntegerField()
    enabled = BooleanField()
    latitude = FloatField()
    longitude = FloatField()
    last_modified = DateTimeField()


def parse_map(map_dict, iteration_num, step):
    pokemons = {}
    pokestops = {}
    gyms = {}

    cells = map_dict['responses']['GET_MAP_OBJECTS']['map_cells']
    for cell in cells:
        for p in cell.get('wild_pokemons', []):
            d_t = datetime.utcfromtimestamp(
                (p['last_modified_timestamp_ms'] +
                 p['time_till_hidden_ms']) / 1000.0)
            printPokemon(p['pokemon_data']['pokemon_id'],p['latitude'],p['longitude'],d_t)
            pokemons[p['encounter_id']] = {
                'encounter_id': b64encode(str(p['encounter_id'])),
github coblo / gui-demo / app / models / votinground.py View on Github external
log = logging.getLogger(__name__)


class VotingRound(peewee.Model):
    """Permission votings"""

    GRANT, REVOKE, SCOPED_GRANT = 0, 1, 2
    VOTE_TYPES = (
        (GRANT, 'Grant'),
        (REVOKE, 'Revoke'),
        (SCOPED_GRANT, 'Scoped Grant'),
    )

    MAX_END_BLOCK = 4294967295

    first_vote = peewee.DateTimeField()
    address = peewee.ForeignKeyField(Address, related_name='votings')
    perm_type = peewee.CharField(choices=Permission.PERM_TYPES)
    start_block = peewee.IntegerField()
    end_block = peewee.IntegerField()
    approbations = peewee.IntegerField()
    vote_type = peewee.SmallIntegerField(choices=VOTE_TYPES, null=True)

    class Meta:
        database = data_db
        primary_key = peewee.CompositeKey('address', 'perm_type', 'start_block', 'end_block')

    def set_vote_type(self):
        if self.start_block == self.end_block == 0:
            self.vote_type = self.REVOKE
        elif self.end_block == 0 and self.end_block == self.MAX_END_BLOCK:
            self.vote_type = self.GRANT
github FederatedAI / FATE / federatedml / util / db_models.py View on Github external
DEFAULT_TAG = 'Za'

class IdLibraryCacheInfo(DataBaseModel):
    f_party_id = CharField(max_length=32)
    f_id_type = CharField(max_length=16)
    f_encrypt_type = CharField(max_length=16)
    f_tag = CharField(max_length=16, default=DEFAULT_TAG)
    f_namespcae = CharField(max_length=128)
    f_version = CharField(max_length=128)
    f_rsa_key_n = CharField(max_length=512)
    f_rsa_key_d = CharField(max_length=512)
    f_rsa_key_e = CharField(max_length=32)
    f_create_datetime = DateTimeField(default=datetime.datetime.now)
    f_update_datetime = DateTimeField(default=datetime.datetime.now)
    f_description = TextField(null=True, default='')

    class Meta:
        db_table = "t_id_library_cache_info"
        primary_key = CompositeKey('f_party_id', 'f_id_type', 'f_encrypt_type', 'f_tag', 'f_namespcae', 'f_version')
github PrefectHQ / prefect / prefect / models.py View on Github external
db_table = 'edges'

deferred_taskrun = pw.DeferredRelation()


class FlowRunModel(PrefectModel):
    """
    Database model for a Prefect FlowRun
    """

    flow = pw.ForeignKeyField(FlowModel, related_name='flow_runs', index=True)

    created = pw.DateTimeField(default=datetime.datetime.now)
    scheduled_start = pw.DateTimeField(null=True, index=True)
    started = pw.DateTimeField(null=True)
    finished = pw.DateTimeField(null=True)
    heartbeat = pw.DateTimeField(null=True)

    progress = pw.FloatField(default=0)

    generated_by = pw.ForeignKeyField(
        deferred_taskrun, null=True, index=True, related_name='generated_flow_runs')

    state = pw.IntegerField(default=0, index=True)
    params = kv.JSONKeyStore(database=db.database)
    scheduled = pw.BooleanField(default=False)

    class Meta:
        db_table = 'flow_runs'


class TaskRunModel(PrefectModel):
github f213 / selfmailbot / src / models.py View on Github external
import uuid

import peewee as pw
import telegram
from envparse import env
from playhouse.db_url import connect

env.read_envfile()

db = connect(env('DATABASE_URL', cast=str, default='sqlite:///db.sqlite'))


class User(pw.Model):
    pk = pw.BigIntegerField(index=True, unique=True)
    created = pw.DateTimeField(constraints=[pw.SQL('DEFAULT CURRENT_TIMESTAMP')])
    full_name = pw.CharField()
    username = pw.CharField(null=True)
    email = pw.CharField(index=True, null=True)
    is_confirmed = pw.BooleanField(default=False, index=True)
    sent_message_count = pw.IntegerField(default=0)
    confirmation = pw.CharField(max_length=36, index=True)
    chat_id = pw.BigIntegerField(unique=True)

    class Meta:
        database = db


def get_user_instance(user: telegram.User, chat_id: int) -> User:
    instance, created = User.get_or_create(
        pk=user.id,
        defaults=dict(
github NBISweden / swefreq / scripts / importer / data_importer / old_db.py View on Github external
class DatasetVersionCurrent(DatasetVersion):
    dataset = ForeignKeyField(Dataset, db_column='dataset_pk', to_field='dataset', related_name='current_version')

    class Meta:
        db_table = 'dataset_version_current'


class SFTPUser(MySQLModel):
    sftp_user     = PrimaryKeyField(db_column='sftp_user_pk')
    user          = ForeignKeyField(User, db_column='user_pk', to_field='user', related_name='sftp_user')
    user_uid      = IntegerField(unique=True)
    user_name     = CharField(null=False)
    password_hash = CharField(null=False)
    account_expires = DateTimeField(null=False)

    class Meta:
        db_table = 'sftp_user'


def get_next_free_uid():
    """
    Returns the next free uid >= 10000, and higher than the current uid's
    from the sftp_user table in the database.
    """
    default = 10000
    next_uid = default
    try:
        current_max_uid = SFTPUser.select(fn.MAX(SFTPUser.user_uid)).get().user_uid
        if current_max_uid:
            next_uid = current_max_uid+1