文章目录
13.8 MySQL 扩展
Peewee 为使用mysql-connector驱动程序或mariadb-connector提供了一个备用数据库实现 。可以在 中找到实现playhouse.mysql_ext。
mysql-connector 的示例用法:
from playhouse.mysql_ext import MySQLConnectorDatabase
# MySQL database implementation that utilizes mysql-connector driver.
db = MySQLConnectorDatabase('my_database', host='1.2.3.4', user='mysql')
mariadb-connector 的示例用法:
from playhouse.mysql_ext import MariaDBConnectorDatabase
# MySQL database implementation that utilizes mysql-connector driver.
db = MariaDBConnectorDatabase('my_database', host='1.2.3.4', user='mysql')
笔记
MariaDBConnectorDatabase不接受以下参数:
- charset(总是 utf8mb4)
- sql_mode
- use_unicode
其他特定于 MySQL 的帮助程序:
class JSONField
class JSONField
在 Python 中扩展TextField和实现透明 JSON 编码和解码。
Match
Match(columns, expr[, modifier=None])
参数:
- columns——单个Field或多个字段的元组。
- expr ( str ) – 全文搜索表达式。
- modifier( str ) – 搜索的可选修饰符,例如’in boolean mode’。
用于构建 MySQL 全文搜索查询的辅助类,形式如下:
MATCH (columns, ...) AGAINST (expr[ modifier])
13.9 数据集 DataSet
数据集模块包含一个高级 API,用于处理以流行的同名项目为模型的数据库。数据集模块的目标是提供:
- 用于处理关系数据的简化 API,与使用 JSON 类似。
- 一种将关系数据导出为 JSON 或 CSV 的简单方法。
- 将 JSON 或 CSV 数据导入关系数据库的简单方法。
一个最小的数据加载脚本可能如下所示:
from playhouse.dataset import DataSet
db = DataSet('sqlite:///:memory:')
table = db['sometable']
table.insert(name='Huey', age=3)
table.insert(name='Mickey', age=5, gender='male')
huey = table.find_one(name='Huey')
print(huey)
# {'age': 3, 'gender': None, 'id': 1, 'name': 'Huey'}
for obj in table:
print(obj)
# {'age': 3, 'gender': None, 'id': 1, 'name': 'Huey'}
# {'age': 5, 'gender': 'male', 'id': 2, 'name': 'Mickey'}
您也可以使用字典 API 插入、更新或删除:
huey = table.find_one(name='Huey')
# {'age': 3, 'gender': None, 'id': 1, 'name': 'Huey'}
# Perform an update by supplying a partial record of changes.
table[1] = {'gender': 'male', 'age': 4}
print(table[1])
# {'age': 4, 'gender': 'male', 'id': 1, 'name': 'Huey'}
# Or insert a new record:
table[3] = {'name': 'Zaizee', 'age': 2}
print(table[3])
# {'age': 2, 'gender': None, 'id': 3, 'name': 'Zaizee'}
# Or delete a record:
del table[3] # Remove the row we just added.
您可以使用freeze()和 thaw()导出或导入数据:
# Export table content to the `users.json` file.
db.freeze(table.all(), format='json', filename='users.json')
# Import data from a CSV file into a new table. Columns will be automatically
# created for each field in the CSV file.
new_table = db['stats']
new_table.thaw(format='csv', filename='monthly_stats.csv')
13.9.1 入门
DataSet对象通过传入格式的数据库 URL 进行初始化dialect://user:password@host/dbname。有关连接到各种数据库的示例,请参阅数据库 URL部分。
# Create an in-memory SQLite database.
db = DataSet('sqlite:///:memory:')
13.9.2 存储数据
要存储数据,我们必须首先获取对表的引用。如果表不存在,会自动创建:
# Get a table reference, creating the table if it does not exist.
table = db['users']
我们现在可以insert()在表中添加新行。如果列不存在,它们将被自动创建:
table.insert(name='Huey', age=3, color='white')
table.insert(name='Mickey', age=5, gender='male')
要更新表中的现有条目,请传入包含新值和过滤条件的字典。用作过滤器的列列表在columns参数中指定。如果未指定过滤列,则将更新所有行。
# Update the gender for "Huey".
table.update(name='Huey', gender='male', columns=['name'])
# Update all records. If the column does not exist, it will be created.
table.update(favorite_orm='peewee')
13.9.3 导入数据
要从外部源(例如 JSON 或 CSV 文件)导入数据,您可以使用该thaw()方法。默认情况下,将为遇到的任何属性创建新列。如果您只想填充已经在表上定义的列,您可以传入strict=True.
# Load data from a JSON file containing a list of objects.
table = dataset['stock_prices']
table.thaw(filename='stocks.json', format='json')
table.all()[:3]
# Might print...
[{'id': 1, 'ticker': 'GOOG', 'price': 703},
{'id': 2, 'ticker': 'AAPL', 'price': 109},
{'id': 3, 'ticker': 'AMZN', 'price': 300}]
13.9.4 使用事务
DataSet 支持使用简单的上下文管理器嵌套事务。
table = db['users']
with db.transaction() as txn:
table.insert(name='Charlie')
with db.transaction() as nested_txn:
# Set Charlie's favorite ORM to Django.
table.update(name='Charlie', favorite_orm='django', columns=['name'])
# jk/lol
nested_txn.rollback()
13.9.5 检查数据库
您可以使用该tables()方法列出当前数据库中的表:
>>> print(db.tables)
['sometable', 'user']
对于给定的表,您可以打印列:
>>> table = db['user']
>>> print(table.columns)
['id', 'age', 'name', 'gender', 'favorite_orm']
我们还可以找出一个表中有多少行:
>>> print(len(db['user']))
3
13.9.6 读取数据
要检索所有行,您可以使用以下all()方法:
# Retrieve all the users.
users = db['user'].all()
# We can iterate over all rows without calling `.all()`
for user in db['user']:
print(user['name'])
可以使用find()和 检索特定对象find_one()。
# Find all the users who like peewee.
peewee_users = db['user'].find(favorite_orm='peewee')
# Find Huey.
huey = db['user'].find_one(name='Huey')
13.9.7 导出数据
要导出数据,请使用该freeze()方法,传入您希望导出的查询:
peewee_users = db['user'].find(favorite_orm='peewee')
db.freeze(peewee_users, format='json', filename='peewee_users.json')
13.9.8 API
class DataSet
class DataSet(url,**kwargs )
参数:
- url – 数据库 URL 或Database实例。有关使用 URL 的详细信息,请参阅数据库 URL以获取示例。
- kwargs –自省 db 时传递给的附加关键字参数 Introspector.generate_models()。
DataSet类提供了用于处理关系数据库的高级 API。
tables
返回存储在数据库中的表列表。该列表在每次访问时动态计算。
getitem(table_name)
提供Table对指定表的引用。如果该表不存在,则将创建该表。
query(sql[, params=None[, commit=True]])
参数:
- sql ( str ) – SQL 查询。
- params ( list ) – 查询的可选参数。
- commit ( bool ) – 查询是否应在执行时提交。
返回:
数据库游标。
对数据库执行提供的查询。
transaction()
创建一个表示新事务(或保存点)的上下文管理器。
freeze(query[, format=‘csv’[, filename=None[, file_obj=None[, encoding=‘utf8’[, **kwargs]]]]])
参数:
- query- A SelectQuery,使用all()或生成~Table.find。
- format——输出格式。默认情况下,支持csv和json。
- filename – 将输出写入的文件名。
- file_obj - 将输出写入的类文件对象。
- encoding ( str ) – 文件编码。
- kwargs – 导出特定功能的任意参数。
thaw(table[, format=‘csv’[, filename=None[, file_obj=None[, strict=False[, encoding=‘utf8’[, **kwargs]]]]]])
参数:
- table ( str ) – 要将数据加载到其中的表的名称。
- 格式——输入格式。默认情况下,支持csv和json。
- filename – 从中读取数据的文件名。
- file_obj - 要从中读取数据的类文件对象。
- strict ( bool ) – 是否存储表中尚不存在的列的值。
- encoding ( str ) – 文件编码。
- kwargs – 导入特定功能的任意参数。
connect()
打开与基础数据库的连接。如果未显式打开连接,则将在第一次执行查询时打开连接。
close()
关闭与底层数据库的连接。
class Table
class Table(dataset, name, model_class)
无索引:
提供用于处理给定表中的行的高级 API。
columns
返回给定表中的列列表。
model_class
动态创建的Model类。
create_index(columns[, unique=False])
在给定列上创建索引:
# Create a unique index on the `username` column.
db['users'].create_index(['username'], unique=True)
insert( **data)
将给定的数据字典插入表中,根据需要创建新列。
update(columns=None, conjunction=None, **data)
使用提供的数据更新表。如果在columns参数中指定了一个或多个列,则数据字典中这些列的值 将用于确定要更新哪些行。
# Update all rows.
db['users'].update(favorite_orm='peewee')
# Only update Huey's record, setting his age to 3.
db['users'].update(name='Huey', age=3, columns=['name'])
find( **query)
查询表中与指定相等条件匹配的行。如果未指定查询,则返回所有行。
peewee_users = db['users'].find(favorite_orm='peewee')
find_one( **query)
返回与指定相等条件匹配的单行。如果没有找到匹配的行,那么None将被返回。
huey = db['users'].find_one(name='Huey')
all()
返回给定表中的所有行。
delete( **query)
删除与给定相等条件匹配的所有行。如果未提供查询,则将删除所有行。
# Adios, Django!
db['users'].delete(favorite_orm='Django')
# Delete all the secret messages.
db['secret_messages'].delete()
freeze([format=‘csv’[, filename=None[, file_obj=None[, **kwargs]]]])
参数:
- format——输出格式。默认情况下,支持csv和json。
- filename – 将输出写入的文件名。
- file_obj - 将输出写入的类文件对象。
- kwargs – 导出特定功能的任意参数。
thaw([format=‘csv’[, filename=None[, file_obj=None[, strict=False[, **kwargs]]]]])
参数:
- format——输入格式。默认情况下,支持csv和json。
- filename – 从中读取数据的文件名。
- file_obj - 要从中读取数据的类文件对象。
- strict ( bool ) – 是否存储表中尚不存在的列的值。
- kwargs – 导入特定功能的任意参数。