Peeweeノートを使う

5459 ワード

1、pythonファイルがインタラクティブモードに入る方法
import IPython
IPython.embed()

2、peeweeモジュールのインストール参考公式サイト
3、peeweeモデルの簡単な構造:
Model class --> Database table
Field class --> Column table
Model instance --> Row in a database table 
from peewee import *
db = SqliteDatabase('people.db')
class Person(Model):
    name = CharField()
    birthday = DateField() is_relative = BooleanField()
    class Meta:
        database = db

class Pet(Model):
    owner = ForeignKeyField(Person, related_name='pets') name = CharField()
    animal_type = CharField()
    class Meta:
        database = db

4、sqlite 3を例に、まず対応モデルのデータテーブルを作成する
>>> db.connect()
>>> db.create_tables([Person, Pet])

5、モデルデータの追加
   :
>>> from datetime import date
>>> uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15), is_relative=True)
>>> uncle_bob.save()
   :
>>> p1 = Person.create(name='p1', birthday=date(1999, 10, 10), is_relative=True)

6、データの削除
>>> p1.delete_instance()

7.1、単一データget()を得る
   :
>>> uncle_bob = Person.select().where(Person.name == 'Bob').get()
   :
>>> uncle_bob = Person.get(Person.name == 'Bob')

7.2、取得データリストselect()
>>> query = Pet.select()
>>> query = Pet.select().where(Pet.animal_type == 'cat')

7.3、join()の使用
query = (Pet.select(Pet, Person).join(Person).where(Person.name == 'Bob'))

7.4、データリスト並べ替えorder_by()
>>> query = Pet.select().where(Pet.owner == uncle_bob).order_by(Pet.name)

7.5、モデル間データ関連
     person pet   
>>> for person in Person.select():
...     print(person.name, person.pets.count())
>>> subquery = Pet.select(fn.COUNT(Pet.id)).where(Pet.owner == Person.id)
>>> query = (Person.select(Person, Pet, subquery.alias('pet_count')).join(Pet, JOIN.LEFT_OUTER).order_by(Person.name))

7.6、条件範囲のデータを取得する
>>> d1940 = date(1940, 1, 1) 
>>> d1960 = date(1960, 1, 1) 
>>> query = (Person.select().where((Person.birthday < d1940) | (Person.birthday > d1960)))
 :      | ,      &

7.7、Personのname頭文字gまたはGのデータを取得する
>>> expression = (fn.Lower(fn.Substr(Person.name, 1, 1)) == 'g')
>>> query = Person.select().where(expression)

7.8、データベースを閉じる
>>> db.close()

以下は簡単な応用
8、モデルデータ構造と関係
database = SqliteDatabase(DATABASE)

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

class User(BaseModel):
    username = CharField(unique=True) password = CharField()
    email = CharField()
    join_date = DateTimeField()

    class Meta:
        order_by = ('username',)

class Relationship(BaseModel):
    from_user = ForeignKeyField(User, related_name='relationships') 
    to_user = ForeignKeyField(User, related_name='       ')

    class Meta: 
        indexes = (
            # Specify a unique multi-column index on from/to-user.
            (('from_user', 'to_user'), True),
        )

class Message(BaseModel):
    user = ForeignKeyField(User)
    content = TextField()
    pub_date = DateTimeField()

    class Meta:
        order_by = ('-pub_date',)
peewee         :
String、Integer、float、Decimal、Boolean、Date、time、datetime、None、Binary

9、テーブルの作成
def create_tables():
    database.connect()
    database.create_tables([User, Relationship, Message])
 :peewee   create_tables()  ,            ,     ,    sqitch           。

10、flaskフレームワークでは一般的に要求前に開き、応答後にデータベースを閉じる
@app.before_request
def before_request(): 
    database.connect()

@app.after_request
def after_request(response): 
    database.close()
    return response

11、照会
    :
def following(self):
    # query other users through the "relationship" table 
    return (User
            .select()
            .join(Relationship, on=Relationship.to_user)
            .where(Relationship.from_user == self))
def followers(self): 
    return (User
            .select()
            .join(Relationship, on=Relationship.from_user)
            .where(Relationship.to_user == self))

12、新しいオブジェクトを作成する
try:
    with database.transaction():
        # Attempt to create the user. If the username is taken, due to the
        # unique constraint, the database will raise an IntegrityError.
        user = User.create(username=request.form['username'],
            password=md5(request.form['password']).hexdigest(),
            email=request.form['email'],
            join_date=datetime.datetime.now()
)
    # mark the user as being 'authenticated' by setting the session vars
    auth_user(user)
    return redirect(url_for('homepage'))
except IntegrityError:
    flash('That username is already taken')

13、<
messages = Message.select().where(Message.user << user.following())