Blog

Blog

PHODAL

Peewee falcon打造高性能python RESTful服务(二)——Peewee初入

Peewee是一个易用轻巧的ORM。

Peewee简介

Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use.

而ORM则是

对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。

Python Peewee

官网来的示例很糟糕,一个简化的示例如下所示:

from peewee import *
import datetime

db = SqliteDatabase('my_database.db', threadlocals=True)

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

不过,却也提供了几个很实用的模型构建脚本。

Peewee pwiz 模型生成

pwiz is a little script that ships with peewee and is capable of introspecting an existing database and generating model code suitable for interacting with the underlying data. If you have a database already, pwiz can give you a nice boost by generating skeleton code with correct column affinities and foreign keys.

类似的示例有一个:

 python -m pwiz --engine=postgresql my_postgresql_database

而我是用它来生成WordPress的模型,于是有:

 python -m pwiz -e mysql "MK_xunzhao" -uroot > blog_models.py

就这样我们生成了WordPress的Models

接着我们要做的就是一个简单的查询。

Peewee WordPress

下面是WordPress的wp_posts生成的models

class WpPosts(BaseModel):
    id = BigIntegerField(db_column='ID', primary_key=True)
    comment_count = BigIntegerField()
    comment_status = CharField()
    guid = CharField()
    menu_order = IntegerField()
    ping_status = CharField()
    pinged = TextField()
    post_author = BigIntegerField(index=True)
    post_content = TextField(index=True)
    post_content_filtered = TextField()
    post_date = DateTimeField()
    post_date_gmt = DateTimeField()
    post_excerpt = TextField()
    post_mime_type = CharField()
    post_modified = DateTimeField()
    post_modified_gmt = DateTimeField()
    post_name = CharField(index=True)
    post_parent = BigIntegerField(index=True)
    post_password = CharField()
    post_status = CharField()
    post_title = TextField(index=True)
    post_type = CharField()
    to_ping = TextField()

    class Meta:
        db_table = 'wp_posts'

而我们查询语句对应的便是:

 blog_posts = WpPosts.select().where(
        (WpPosts.post_status == "publish") &
        (WpPosts.post_type == "post")
    ).offset(offset).limit(10)

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签