小奥姆
peewee的Python项目详细描述
小便
小虫子是一种简单的小虫子。它有很少(但表达)的概念,使它易于学习和直观使用。
- 一种小型的、有表现力的orm
- python 2.7+和3.4+(使用3.6开发)
- 支持sqlite、mysql和postgresql
- 吨extensions
小便新手?这些可能有帮助:
- Quickstart
- Example twitter app
- Using peewee interactively
- Models and fields
- Querying
- Relationships and joins
示例
定义模型类似于django或sqlalchemy:
frompeeweeimport*importdatetimedb=SqliteDatabase('my_database.db')classBaseModel(Model):classMeta:database=dbclassUser(BaseModel):username=CharField(unique=True)classTweet(BaseModel):user=ForeignKeyField(User,backref='tweets')message=TextField()created_date=DateTimeField(default=datetime.datetime.now)is_published=BooleanField(default=True)
连接到数据库并创建表:
db.connect()db.create_tables([User,Tweet])
创建几行:
charlie=User.create(username='charlie')huey=User(username='huey')huey.save()# No need to set `is_published` or `created_date` since they# will just use the default values we specified.Tweet.create(user=charlie,message='My first tweet')
查询具有表现力和可组合性:
# A simple query selecting a user.User.get(User.username=='charlie')# Get tweets created by one of several users.usernames=['charlie','huey','mickey']users=User.select().where(User.username.in_(usernames))tweets=Tweet.select().where(Tweet.user.in_(users))# We could accomplish the same using a JOIN:tweets=(Tweet.select().join(User).where(User.username.in_(usernames)))# How many tweets were published today?tweets_today=(Tweet.select().where((Tweet.created_date>=datetime.date.today())&(Tweet.is_published==True)).count())# Paginate the user table and show me page 3 (users 41-60).User.select().order_by(User.username).paginate(3,20)# Order users by the number of tweets they've created:tweet_ct=fn.Count(Tweet.id)users=(User.select(User,tweet_ct.alias('ct')).join(Tweet,JOIN.LEFT_OUTER).group_by(User).order_by(tweet_ct.desc()))# Do an atomic updateCounter.update(count=Counter.count+1).where(Counter.url==request.url)
学习更多
查看documentation以获取更多示例。
具体问题?在irc.freenode.net上的“peewee”频道上闲逛,或者发邮件到邮件列表http://groups.google.com/group/peewee-orm。如果您想报告一个bug,请在github上create a new issue。
还想知道更多信息吗?
我写了很多关于用peewee(通常是flask)构建应用程序和web服务的博客文章。如果您希望看到一些使用peewee的实际应用程序,以下资源可能会很有用:
- Building a note-taking app with Flask and Peewee以及Part 2和Part 3。
- Analytics web service built with Flask and Peewee。
- Personalized news digest (with a boolean query parser!)。
- Structuring Flask apps with Peewee。
- Creating a lastpass clone with Flask and Peewee。
- Creating a bookmarking web-service that takes screenshots of your bookmarks。
- Building a pastebin, wiki and a bookmarking service using Flask and Peewee。
- Encrypted databases with Python and SQLCipher。
- Dear Diary: An Encrypted, Command-Line Diary with Peewee。
- Query Tree Structures in SQLite using Peewee and the Transitive Closure Extension。