How to use the peewee.Model 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 klen / flask-restler / tests / test_peewee.py View on Github external
import peewee as pw
import datetime as dt
import marshmallow as ma
from playhouse.db_url import connect


database = connect('sqlite:///:memory:')


class Role(pw.Model):

    name = pw.CharField(255, default='user')

    class Meta:
        database = database


class User(pw.Model):

    created = pw.DateTimeField(default=dt.datetime.utcnow)
    login = pw.CharField(255)
    name = pw.CharField(255, null=True)
    password = pw.CharField(127, null=True)
    is_active = pw.BooleanField(default=True)

    role = pw.ForeignKeyField(Role, null=True)
github NBISweden / swefreq / backend / db.py View on Github external
TextField,
                    fn)
from playhouse.postgres_ext import ArrayField, BinaryJSONField, PostgresqlExtDatabase

import settings

# pylint: disable=no-member
database = PostgresqlExtDatabase(settings.psql_name,
                                 user=settings.psql_user,
                                 password=settings.psql_pass,
                                 host=settings.psql_host,
                                 port=settings.psql_port,
                                 register_hstore=False)
# pylint: enable=no-member

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


class EnumField(Field):
    db_field = 'string'  # The same as for CharField

    def __init__(self, choices=None, *args, **kwargs):
        self.values = choices or []
        super().__init__(*args, **kwargs)

    def db_value(self, value):
        if value not in self.values:
            raise ValueError("Illegal value for '{}'".format(self.column_name))
        return value
github tsileo / bakthat / bakthat / models.py View on Github external
def db_value(self, value):
        return json.dumps(value)

    def python_value(self, value):
        try:
            return json.loads(value)
        except:
            return value


class BaseModel(peewee.Model):
    class Meta:
        database = database


class SyncedModel(peewee.Model):
    class Meta:
        database = database


class History(BaseModel):
    """History for sync."""
    data = JsonField()
    ts = peewee.IntegerField(index=True)
    action = peewee.CharField(index=True)
    model = peewee.CharField(index=True)
    pk = peewee.CharField(index=True)

    class Meta:
        db_table = 'history'
github coleifer / peewee / bench / peewee_bench / models.py View on Github external
import peewee


test_db = peewee.SqliteDatabase('test_pw.db')

class User(peewee.Model):
    username = peewee.CharField()
    active = peewee.BooleanField(default=False)

    class Meta:
        database = test_db


class Blog(peewee.Model):
    user = peewee.ForeignKeyField(User)
    name = peewee.CharField()

    class Meta:
        database = test_db


class Entry(peewee.Model):
github marshmallow-code / marshmallow / examples / peewee_example.py View on Github external
Schema,
    fields,
    validate,
    pre_load,
    post_dump,
    post_load,
    ValidationError,
)

app = Flask(__name__)
db = pw.SqliteDatabase("/tmp/todo.db")

###### MODELS #####


class BaseModel(pw.Model):
    """Base model class. All descendants share the same database."""

    class Meta:
        database = db


class User(BaseModel):
    email = pw.CharField(max_length=80, unique=True)
    password = pw.CharField()
    joined_on = pw.DateTimeField()


class Todo(BaseModel):
    content = pw.TextField()
    is_done = pw.BooleanField(default=False)
    user = pw.ForeignKeyField(User)
github jpalladino84 / Python-Roguelike-Framework / dungeon / models.py View on Github external
self.x2 = x + w
        self.y2 = y + h

    def center(self):
        center_x = (self.x1 + self.x2) / 2
        center_y = (self.y1 + self.y2) / 2

        return int(floor(center_x)), int(floor(center_y))

    def intersect(self, other):
        # returns true if this rectangle intersects with another one
        return (self.x1 <= other.x2 and self.x2 >= other.x1 and
                self.y1 <= other.y2 and self.y2 >= other.y1)


class DungeonObject(Model):
    """
    An object that is used to keep track of
    location, and whether it blocks another object from moving through it.

    DungeonObject(
        coords=(10, 20),
        blocks=(True | False)
    )
    """
    class Meta(object):
        database = database

    coords = CharField(max_length=20)
    blocks = BooleanField()
github poljar / matrix-nio / nio / store / models.py View on Github external
# Please don't remove this.
# This is a workaround for this bug: https://bugs.python.org/issue27400
class DateField(TextField):
    def python_value(self, value):  # pragma: no cover
        format = "%Y-%m-%d %H:%M:%S.%f"
        try:
            return datetime.strptime(value, format)
        except TypeError:
            return datetime(*(time.strptime(value, format)[0:6]))

    def db_value(self, value):  # pragma: no cover
        return value.strftime("%Y-%m-%d %H:%M:%S.%f")


class LegacyAccounts(Model):
    account = ByteField()
    device_id = TextField(unique=True)
    shared = BooleanField()
    user_id = TextField(primary_key=True)

    class Meta:
        table_name = "accounts"


class LegacyDeviceKeys(Model):
    curve_key = TextField()
    deleted = BooleanField()
    device = ForeignKeyField(
        column_name="device_id",
        field="device_id",
        model=LegacyAccounts,
github Polsaker / throat / migrations / 001_initial.py View on Github external
class Meta:
            table_name = "sub_post_comment_vote"

    @migrator.create_model
    class SubPostMetadata(pw.Model):
        xid = pw.PrimaryKeyField()
        key = pw.CharField(max_length=255, null=True)
        pid = pw.ForeignKeyField(backref='subpostmetadata_set', column_name='pid', field='pid', model=migrator.orm['sub_post'], null=True)
        value = pw.CharField(max_length=255, null=True)

        class Meta:
            table_name = "sub_post_metadata"

    @migrator.create_model
    class SubPostPollOption(pw.Model):
        id = pw.AutoField()
        pid = pw.ForeignKeyField(backref='subpostpolloption_set', column_name='pid', field='pid', model=migrator.orm['sub_post'])
        text = pw.CharField(max_length=255)

        class Meta:
            table_name = "sub_post_poll_option"

    @migrator.create_model
    class SubPostPollVote(pw.Model):
        id = pw.AutoField()
        pid = pw.ForeignKeyField(backref='subpostpollvote_set', column_name='pid', field='pid', model=migrator.orm['sub_post'])
        uid = pw.ForeignKeyField(backref='subpostpollvote_set', column_name='uid', field='uid', model=migrator.orm['user'])
        vid = pw.ForeignKeyField(backref='votes', column_name='vid', field='id', model=migrator.orm['sub_post_poll_option'])

        class Meta:
            table_name = "sub_post_poll_vote"
github klen / muffin / example / migrations / 000_initial.py View on Github external
> migrator.create_table(model)
    > migrator.drop_table(model, cascade=True)
    > migrator.add_columns(model, **fields)
    > migrator.drop_columns(models, *names, cascade=True)
    > migrator.rename_column(model, old_name, new_name)
    > migrator.rename_table(model, new_name)
    > migrator.add_index(model, *columns, unique=False)
    > migrator.drop_index(model, index_name)
    > migrator.add_not_null(model, name)
    > migrator.drop_not_null(model, name)

    """

    @migrator.create_table
    class User(pw.Model):
        username = pw.CharField()
        email = pw.CharField(unique=True)
        password = pw.CharField()
        is_super = pw.BooleanField(default=False)

    @migrator.create_table
    class Test(pw.Model):
        data = pw.CharField()

    @migrator.create_table
    class Token(pw.Model):
        provider = pw.CharField()
        token = pw.CharField()
        token_secret = pw.CharField(null=True)
        user = pw.ForeignKeyField(User)
github its-a-feature / Apfell / apfell-docker / app / database_models / model.py View on Github external
database = apfell_db

    def to_json(self):
        r = {}
        for k in self._data.keys():
            try:
                r[k] = getattr(self, k)
            except:
                r[k] = json.dumps(getattr(self, k), default=lambda o: o.to_json())
        return r

    def __str__(self):
        return str(self.to_json())


class ATTACKCommand(p.Model):
    attack = p.ForeignKeyField(ATTACK, null=False)
    command = p.ForeignKeyField(Command, null=False)

    class Meta:
        database = apfell_db

    def to_json(self):
        r = {}
        for k in self._data.keys():
            try:
                if k == 'attack':
                    r['t_num'] = getattr(self, k).t_num
                    r['attack_name'] = getattr(self, k).name
                elif k == 'command':
                    r[k] = getattr(self, k).cmd
                    r['command_id'] = getattr(self, k).id