【Python百日进阶-Web开发-Peewee】Day243 - 交互式使用 Peewee、贡献

文章目录

  • 四、交互式使用 Peewee
  • 五、贡献
    • 5.1 补丁
    • 5.2 错误
    • 5.3 问题

四、交互式使用 Peewee

http://docs.peewee-orm.com/en/latest/peewee/interactive.html
Peewee 包含用于从 Python 解释器或类似 Jupyter notebook 的东西交互工作的助手。对于这个例子,我们假设我们有一个预先存在的 Sqlite 数据库,它具有以下简单模式:

CREATE TABLE IF NOT EXISTS "event" (
    "id" INTEGER NOT NULL PRIMARY KEY,
    "key" TEXT NOT NULL,
    "timestamp" DATETIME NOT NULL,
    "metadata" TEXT NOT NULL);

为了尝试从交互式解释器会话中查询该数据库,我们将启动解释器并导入以下帮助程序:

  • peewee.SqliteDatabase- 引用“events.db”
  • playhouse.reflection.generate_models- 从现有数据库生成模型。
  • playhouse.reflection.print_model- 查看模型定义。
  • playhouse.reflection.print_table_sql- 查看表SQL。
    我们的终端会话可能如下所示:
>>> from peewee import SqliteDatabase
>>> from playhouse.reflection import generate_models, print_model, print_table_sql
>>>

该generate_models()函数将自省数据库并为找到的所有表生成模型类。这是一种方便的入门方式,可以节省大量打字时间。该函数返回一个以表名为键的字典,生成的模型作为对应的值:

>>> db = SqliteDatabase('events.db')
>>> models = generate_models(db)
>>> list(models.items())
[('events', <Model: event>)]

>>> globals().update(models)  # Inject models into global namespace.
>>> event
<Model: event>

要查看模型定义,其中列出了模型的字段和数据类型,我们可以使用以下print_model()函数:

>>> print_model(event)
event
  id AUTO
  key TEXT
  timestamp DATETIME
  metadata TEXT

如果您发现它更易于阅读,我们还可以为自省模型生成 SQL。这应该匹配自省数据库中的实际表定义:CREATE TABLE

>>> print_table_sql(event)
CREATE TABLE IF NOT EXISTS "event" (
  "id" INTEGER NOT NULL PRIMARY KEY,
  "key" TEXT NOT NULL,
  "timestamp" DATETIME NOT NULL,
  "metadata" TEXT NOT NULL)

现在我们已经熟悉了我们正在使用的表的结构,我们可以对生成的event模型运行一些查询:

>>> for e in event.select().order_by(event.timestamp).limit(5):
...     print(e.key, e.timestamp)
...
e00 2019-01-01 00:01:00
e01 2019-01-01 00:02:00
e02 2019-01-01 00:03:00
e03 2019-01-01 00:04:00
e04 2019-01-01 00:05:00

>>> event.select(fn.MIN(event.timestamp), fn.MAX(event.timestamp)).scalar(as_tuple=True)
(datetime.datetime(2019, 1, 1, 0, 1), datetime.datetime(2019, 1, 1, 1, 0))

>>> event.select().count()  # Or, len(event)
60

有关这些 API 和其他类似反射实用程序的更多信息,请参阅playhouse 扩展 文档的反射部分。

要为现有数据库生成包含模型定义的实际 Python 模块,您可以使用命令行pwiz工具。这是一个简单的例子:

$ pwiz -e sqlite events.db > events.py

该events.py文件现在将是一个可导入模块,其中包含一个数据库实例(引用events.db)以及在数据库中找到的任何表的模型定义。pwiz做了一些额外的好事情,比如内省索引和为NULL/ 约束添加适当的标志等。NOT NULL

本节讨论的 API:

  • generate_models()

  • print_model()

  • print_table_sql()
    实例上还提供了更多低级 API Database:

  • Database.get_tables()

  • Database.get_indexes()

  • Database.get_columns()(对于给定的表)

  • Database.get_primary_keys()(对于给定的表)

  • Database.get_foreign_keys()(对于给定的表)

五、贡献

http://docs.peewee-orm.com/en/latest/peewee/contributing.html
为了不断改进,Peewee 需要像您这样的开发人员的帮助。无论是贡献补丁、提交错误报告,还是只是提出和回答问题,您都在帮助 Peewee 成为一个更好的库。

在本文档中,我将描述一些您可以提供帮助的方法。

5.1 补丁

您是否对新功能有想法,或者您是否想改进笨重的 API?在编写代码并提交拉取请求之前,请在 GitHub 上打开一个新问题来描述您提出的更改。这不必是任何正式的东西,只是对您想做的事情和原因的描述。

准备就绪后,您可以提交包含更改的拉取请求。成功的补丁将具有以下内容:

  • 单元测试。
  • 文档,包括散文形式和通用API 文档。
  • 在风格上与 Peewee 代码库的其余部分一致的代码。

5.2 错误

如果你发现了一个错误,请检查它是否已经被报告,如果没有,请在 GitHub 上创建一个问题。您包含的信息越多,错误得到修复的速度就越快,因此请尝试包含以下内容:

  • 回溯和错误消息(请格式化您的代码!)
  • 重现错误的代码或代码的相关部分
  • Peewee版本:python -c “from peewee import version; print(version)”
  • 您正在使用哪个数据库
    如果您在代码中发现了错误并提交了失败的测试用例,那么向您致敬,您就是英雄!

5.3 问题

如果您对如何使用 peewee 做某事有疑问,那么我建议:

  • 在 StackOverflow 上提问。我几乎每天都会检查 SO 是否有新的 peewee 问题并尝试回答它们。这还具有保存问题和答案以供其他人查找的好处。
  • 在邮件列表中询问,https://groups.google.com/group/peewee-orm
Using Peewee Interactively
Peewee contains helpers for working interactively from a Python interpreter or something like a Jupyter notebook. For this example, we’ll assume that we have a pre-existing Sqlite database with the following simple schema:

CREATE TABLE IF NOT EXISTS "event" (
    "id" INTEGER NOT NULL PRIMARY KEY,
    "key" TEXT NOT NULL,
    "timestamp" DATETIME NOT NULL,
    "metadata" TEXT NOT NULL);
To experiment with querying this database from an interactive interpreter session, we would start our interpreter and import the following helpers:

peewee.SqliteDatabase - to reference the “events.db”
playhouse.reflection.generate_models - to generate models from an existing database.
playhouse.reflection.print_model - to view the model definition.
playhouse.reflection.print_table_sql - to view the table SQL.
Our terminal session might look like this:

>>> from peewee import SqliteDatabase
>>> from playhouse.reflection import generate_models, print_model, print_table_sql
>>>
The generate_models() function will introspect the database and generate model classes for all the tables that are found. This is a handy way to get started and can save a lot of typing. The function returns a dictionary keyed by the table name, with the generated model as the corresponding value:

>>> db = SqliteDatabase('events.db')
>>> models = generate_models(db)
>>> list(models.items())
[('events', )]

>>> globals().update(models)  # Inject models into global namespace.
>>> event

To take a look at the model definition, which lists the model’s fields and data-type, we can use the print_model() function:

>>> print_model(event)
event
  id AUTO
  key TEXT
  timestamp DATETIME
  metadata TEXT
We can also generate a SQL CREATE TABLE for the introspected model, if you find that easier to read. This should match the actual table definition in the introspected database:

>>> print_table_sql(event)
CREATE TABLE IF NOT EXISTS "event" (
  "id" INTEGER NOT NULL PRIMARY KEY,
  "key" TEXT NOT NULL,
  "timestamp" DATETIME NOT NULL,
  "metadata" TEXT NOT NULL)
Now that we are familiar with the structure of the table we’re working with, we can run some queries on the generated event model:

>>> for e in event.select().order_by(event.timestamp).limit(5):
...     print(e.key, e.timestamp)
...
e00 2019-01-01 00:01:00
e01 2019-01-01 00:02:00
e02 2019-01-01 00:03:00
e03 2019-01-01 00:04:00
e04 2019-01-01 00:05:00

>>> event.select(fn.MIN(event.timestamp), fn.MAX(event.timestamp)).scalar(as_tuple=True)
(datetime.datetime(2019, 1, 1, 0, 1), datetime.datetime(2019, 1, 1, 1, 0))

>>> event.select().count()  # Or, len(event)
60
For more information about these APIs and other similar reflection utilities, see the Reflection section of the playhouse extensions document.

To generate an actual Python module containing model definitions for an existing database, you can use the command-line pwiz tool. Here is a quick example:

$ pwiz -e sqlite events.db > events.py
The events.py file will now be an import-able module containing a database instance (referencing the events.db) along with model definitions for any tables found in the database. pwiz does some additional nice things like introspecting indexes and adding proper flags for NULL/NOT NULL constraints, etc.

The APIs discussed in this section:

generate_models()
print_model()
print_table_sql()
More low-level APIs are also available on the Database instance:

Database.get_tables()
Database.get_indexes()
Database.get_columns() (for a given table)
Database.get_primary_keys() (for a given table)
Database.get_foreign_keys() (for a given table)

你可能感兴趣的:(Python,python,数据库,sqlite)