版權聲明:自由轉(zhuǎn)載-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0
最近有個ETL取數(shù)項目扔役, 存儲端使用數(shù)據(jù)庫, 必要時候還要進行多線程轉(zhuǎn)換匙赞, 而mysql 多線程多進程讀寫需要注意的地方太多, 多線程調(diào)試又非常麻煩妖碉。所有選擇python orm涌庭。
python 中orm模塊非常之多, 優(yōu)缺點也很明顯欧宜, 有功能比較全面的sqlalchemy坐榆, 也有django framework提供的ORM。 總之每個都優(yōu)點冗茸, 但也單來缺點席镀。 如sqlalchemy功能多, 相對學習曲線就長了夏漱。 django framework提供的models操作豪诲, 有很多django特性, 但這些特性也能帶來缺點挂绰。
這里有一篇博客專門講了python 眾多ORM的選擇,
本篇博客屎篱, 研究的是peewee。 超級輕量的一個ORM模塊, 而且操作數(shù)據(jù)非常之簡單交播。
根據(jù)數(shù)據(jù)庫表生成模型
:::shell
python -m pwiz -e mysql -H localhost -p3306 -uroot -Pkkd93kd web_db > db.py
模型樣例
:::python
from peewee import *
database = MySQLDatabase('web_db', **{'host': 'localhost', 'password': 'kkd93kd ', 'port': 3306, 'user': 'root'})
class UnknownField(object):
pass
class BaseModel(Model):
class Meta:
database = database
class SyShieldOrder(BaseModel):
_id = PrimaryKeyField()
order_up_day = IntegerField(null=True)
order_up_hours = IntegerField(null=True)
order_up_moon = IntegerField(null=True)
order_up_quarter = IntegerField(null=True)
order_up_week = IntegerField(null=True)
order_up_year = IntegerField(null=True)
tu_shopid = CharField(null=True)
class Meta:
db_table = 'sy_shield_order'
class SyShieldUser(BaseModel):
_id = PrimaryKeyField()
tu_account = CharField(null=True)
tu_area = CharField(null=True)
tu_city = CharField(null=True)
tu_commence = DateField(null=True)
tu_contract = DateField(null=True)
tu_cost = IntegerField(null=True)
tu_domain = CharField(null=True)
tu_nick = CharField(null=True)
tu_platform = CharField(null=True)
tu_province = CharField(null=True)
tu_realcost = IntegerField(null=True)
tu_shopid = CharField(null=True)
tu_version = CharField(null=True)
class Meta:
db_table = 'sy_shield_user'
操作
:::python
from datetime import datetime
from src import *
database.connect()
for i in SyShieldUser.select():
print i.tu_account
print i.__dict__
for i in range(10):
data = {
'tu_account': "user_%s" % str(i),
'tu_area': "HuaDong",
'tu_city': "Shanghai",
}
print SyShildUser.create(tu_account="user", tu_area="HuaDong", tu_city="Shanghai", tu_shopid="100000%s" % str(i))