data61/anonlink-entity-service

Replace low level database operations with an ORM

Open

#133 创建于 2018年4月18日

在 GitHub 查看
 (2 评论) (0 反应) (0 负责人)Python (8 fork)github user discovery
P4: nice to havebest practiceeffort2: medium (day)help wanted

仓库指标

Star
 (29 star)
PR 合并指标
 (PR 指标待抓取)

描述

I quite like the look of peewee although SqlAlchemy is the standard.

For example we would define models for our tables:

class Project(BaseModel):
    access_token = pw.TextField()
    chunk_size = pw.BigIntegerField(constraints=[pw.SQL("DEFAULT '-1'::integer")])
    notes = pw.TextField(null=True)
    parties = pw.IntegerField(constraints=[pw.SQL("DEFAULT 2")], null=True)
    ready = pw.BooleanField(constraints=[pw.SQL("DEFAULT false")])
    resource = pw.CharField(column_name='resource_id', unique=True)
    result_type = UnknownField()  # Or use USER-DEFINED
    schema = BinaryJSONField()
    threshold = pw.FloatField()
    time_added = pw.DateTimeField(constraints=[pw.SQL("DEFAULT CURRENT_TIMESTAMP")], null=True)
    time_completed = pw.DateTimeField(null=True)
    time_started = pw.DateTimeField(null=True)

    class Meta:
        table_name = 'projects'

We can then create tables:

def create_tables():
    db.connect()
    Project.create_table(True)

Our database queries change to ORM code - example from the docs:

for tweet in Tweet.select().where(Tweet.user == user, Tweet.is_published == True):
    print(tweet.user.username, '->', tweet.message)

贡献者指南