首页 > 编程 > Python > 正文

浅谈Python peewee 使用经验

2020-02-16 10:26:19
字体:
来源:转载
供稿:网友

本文使用案例是基于 python2.7 实现

以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作。所以,没有使用过 peewee,可以先阅读文档

正确性和覆盖面有待提高,如果遇到新的问题欢迎讨论。

一、介绍

Peewee 是一个简单、轻巧的 Python ORM。

    简单、轻巧、富有表现力(原词 expressive )的ORM 支持python版本 2.6+ 和 3.2+ 支持数据库包括:sqlite, mysql and postgresql 包含一堆实用的扩展在 playhouse 模块中

总而言之,peewee 可以完全可以应付个人或企业的中小型项目的 Model 层,上手容易,功能很强大。

二、基本使用方法

from peewee import *db = SqliteDatabase('people.db')class BaseModel(Model):  class Meta:    database = db # This model uses the "people.db" database.class Person(BaseModel):  name = CharField()  birthday = DateField()  is_relative = BooleanField()  

基本的使用方法,推荐阅读文档--quickstart

三、推荐使用姿势

下面介绍一些我在使用过程的经验和遇到的坑,希望可以帮助大家更好的使用 peewee。

3.1 连接数据库

连接数据库时,推荐使用 playhouse 中的 db_url 模块。db_url 的 connect 方法可以通过传入的 URL 字符串,生成数据库连接。

3.1.1 connect(url, **connect_params)

通过传入的 url 字符串,创建一个数据库实例

url形如:

    mysql://user:passwd@ip:port/my_db 将创建一个 本地 MySQL 的 my_db 数据库的实例(will create a MySQLDatabase instance) mysql+pool://user:passwd@ip:port/my_db?charset=utf8&max_connections=20&stale_timeout=300 将创建一个本地 MySQL 的 my_db 的连接池,最大连接数为20(In a multi-threaded application, up to max_connections will be opened. Each thread (or, if using gevent, greenlet) will have it's own connection. ),超时时间为300秒(will create a PooledMySQLDatabase instance)

注意:charset 默认为utf8。如需要支持 emoji ,charset 设置为utf8mb4,同时保证创建数据库时的字符集设置正确CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;。

支持的 schemes:

    apsw: APSWDatabase mysql: MySQLDatabase mysql+pool: PooledMySQLDatabase postgres: PostgresqlDatabase postgres+pool: PooledPostgresqlDatabase postgresext: PostgresqlExtDatabase postgresext+pool: PooledPostgresqlExtDatabase sqlite: SqliteDatabase sqliteext: SqliteExtDatabase sqlite+pool: PooledSqliteDatabase sqliteext+pool: PooledSqliteExtDatabase

3.1.2 推荐姿势

from playhouse.db_url import connectfrom dock.common import config# url: mysql+pool://root:root@127.0.0.1:3306/appmanage?max_connections=300&stale_timeout=300mysql_config_url = config_dict.get('config').get('mysql').get('url')db = connect(url=mysql_config_url)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表