当前位置: 首页 > news >正文

【Python百日进阶-Web开发-Peewee】Day244 - 数据库 Postgresql、CockroachDB

文章目录

  • 六、数据库
    • 6.1 初始化数据库
    • 6.2 使用 Postgresql
      • 6.2.1 隔离级别
    • 6.3 使用 CockroachDB

六、数据库

http://docs.peewee-orm.com/en/latest/peewee/database.html
PeeweeDatabase对象表示与数据库的连接。该类Database使用打开数据库连接所需的所有信息进行实例化,然后可用于:

  • 打开和关闭连接。
  • 执行查询。
  • 管理事务(和保存点)。
  • 内省表、列、索引和约束。
    Peewee 支持 SQLite、MySQL 和 Postgres。每个数据库类都提供了一些基本的、特定于数据库的配置选项。
from peewee import *# SQLite database using WAL journal mode and 64MB cache.
sqlite_db = SqliteDatabase('/path/to/app.db', pragmas={'journal_mode': 'wal','cache_size': -1024 * 64})# Connect to a MySQL database on network.
mysql_db = MySQLDatabase('my_app', user='app', password='db_password',host='10.1.0.8', port=3306)# Connect to a Postgres database.
pg_db = PostgresqlDatabase('my_app', user='postgres', password='secret',host='10.1.0.9', port=5432)

Peewee 通过特定于数据库的扩展模块为 SQLite、Postgres 和 CockroachDB 提供高级支持。要使用扩展功能,请导入适当的特定于数据库的模块并使用提供的数据库类:

from playhouse.sqlite_ext import SqliteExtDatabase# Use SQLite (will register a REGEXP function and set busy timeout to 3s).
db = SqliteExtDatabase('/path/to/app.db', regexp_function=True, timeout=3,pragmas={'journal_mode': 'wal'})from playhouse.postgres_ext import PostgresqlExtDatabase# Use Postgres (and register hstore extension).
db = PostgresqlExtDatabase('my_app', user='postgres', register_hstore=True)from playhouse.cockroachdb import CockroachDatabase# Use CockroachDB.
db = CockroachDatabase('my_app', user='root', port=26257, host='10.1.0.8')# CockroachDB connections may require a number of parameters, which can
# alternatively be specified using a connection-string.
db = CockroachDatabase('postgresql://...')

有关数据库扩展的更多信息,请参见:

  • Postgresql 扩展
  • SQLite 扩展
  • Cockroach数据库
  • Sqlcipher 后端(加密的 SQLite 数据库)。
  • apsw,一个高级的 sqlite 驱动程序
  • SqliteQ

6.1 初始化数据库

初始化方法需要数据库的Database名称作为第一个参数。后续的关键字参数在建立连接时传递给底层数据库驱动程序,允许您轻松传递特定于供应商的参数。

例如,对于 Postgresql,通常需要在创建连接时指定host, user和。password这些不是标准的 Peewee参数,所以在创建连接时Database会直接传回 :psycopg2

db = PostgresqlDatabase('database_name',  # Required by Peewee.user='postgres',  # Will be passed directly to psycopg2.password='secret',  # Ditto.host='db.mysite.com')  # Ditto.

作为另一个示例,pymysql驱动程序接受charset不是标准 Peewee参数的Database参数。要设置此值,只需charset与其他值一起传入:

db = MySQLDatabase('database_name', user='www-data', charset='utf8mb4')

有关可用参数,请参阅数据库驱动程序的文档:

  • Postgres:psycopg2
  • MySQL:MySQL数据库
  • MySQL:pymysql
  • SQLite:sqlite3
  • CockroachDB:参见psycopg2

6.2 使用 Postgresql

要连接到 Postgresql 数据库,我们将使用 PostgresqlDatabase. 第一个参数始终是数据库的名称,之后您可以指定任意psycopg2 参数。

psql_db = PostgresqlDatabase('my_database', user='postgres')class BaseModel(Model):"""A base model that will use our Postgresql database"""class Meta:database = psql_dbclass User(BaseModel):username = CharField()

Playhouse,Peewee的扩展包含一个Postgresql 扩展模块,它提供了许多 postgres 特定的功能,例如:

  • 数组
  • HStore
  • JSON
  • 服务器端游标
  • 更多!
    如果您想使用这些很棒的功能,请使用 PostgresqlExtDatabase模块中的playhouse.postgres_ext:
from playhouse.postgres_ext import PostgresqlExtDatabasepsql_db = PostgresqlExtDatabase('my_database', user='postgres')

6.2.1 隔离级别

从 Peewee 3.9.7 开始,可以使用以下符号常量将隔离级别指定为初始化参数psycopg2.extensions:

from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLEdb = PostgresqlDatabase('my_app', user='postgres', host='db-host',isolation_level=ISOLATION_LEVEL_SERIALIZABLE)

笔记

在旧版本中,您可以手动设置底层 psycopg2 连接的隔离级别。这可以一次性完成:

db = PostgresqlDatabase(...) 
conn = db.connection()  # returns current connection.from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE 
conn.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE) 

要在每次创建连接时运行它,子类化并实现_initialize_database()为此目的而设计的钩子:

class SerializedPostgresqlDatabase(PostgresqlDatabase):def _initialize_connection(self, conn):conn.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)

6.3 使用 CockroachDB

CockroachDatabase使用以下定义的数据库类连接到 CockroachDB (CRDB) playhouse.cockroachdb:

from playhouse.cockroachdb import CockroachDatabasedb = CockroachDatabase('my_app', user='root', port=26257, host='localhost')

如果您使用Cockroach Cloud,您可能会发现使用连接字符串指定连接参数更容易:

db = CockroachDatabase('postgresql://root:secret@host:26257/defaultdb...')

笔记

CockroachDB 需要psycopg2(postgres) Python 驱动程序。

笔记

CockroachDB 安装和入门指南可以在这里找到:https
😕/www.cockroachlabs.com/docs/stable/install-cockroachdb.html

CRDB 提供客户端事务重试,可使用特殊的CockroachDatabase.run_transaction()辅助方法获得。此方法接受一个可调用对象,该可调用对象负责执行任何可能需要重试的事务语句。

最简单的例子run_transaction():

def create_user(email):# Callable that accepts a single argument (the database instance) and# which is responsible for executing the transactional SQL.def callback(db_ref):return User.create(email=email)return db.run_transaction(callback, max_attempts=10)huey = create_user('huey@example.com')

笔记

如果在给定的cockroachdb.ExceededMaxAttempts尝试次数后无法提交事务,则会引发异常。如果 SQL
格式错误、违反约束等,则该函数将向调用者引发异常。

有关更多信息,请参阅:

  • CRDB 扩展文档
  • 使用 CockroachDB 进行 SSL 配置
  • 数组(特定于 postgres,但适用于 CRDB)
  • JSON(特定于 postgres,但适用于 CRDB)
http://www.lryc.cn/news/92959.html

相关文章:

  • Vue 中的列表渲染
  • java 中的关键字
  • python序列化和结构化数据详解
  • PoseiSwap的趋势性如何体现?
  • 西南交通大学智能监测 培训课程练习4
  • 设备树的引入及简明教程
  • MM32F3273G8P火龙果开发板MindSDK开发教程12 -获取msa311加速器的敲击事件
  • Maven聚合
  • [架构之路-211]- 需求- 软架构前的需求理解:ADMEMS标准化、有序化、结构化、层次化需求矩阵 =》需求框架
  • 基于前推回代法的连续潮流计算研究【IEEE33节点】(Matlab代码实现)
  • 【双向链表】
  • POSTGRESQL NEON - Serverless 式的POSTGRESQL 数据库的独特技能 分支数据
  • 数据分布——长尾分布的处理
  • 集合导题、刷题、考试全套完整流程,专业强大的功能,提高刷题学习效率和企业的培训效率
  • 【机器学习】采样方法
  • Seata TCC 模式理论学习、生产级使用示例搭建及注意事项 | Spring Cloud55
  • 一文详解:Vue3中使用Vue Router
  • C++开发—远程控制
  • 【Python基础】Python数据容器(集合)
  • 高通 Camera HAL3:集成camxoverridesettings.txt到整机版本
  • PHP面试题大全
  • Linux发送接收邮件
  • SpringBoot-【回顾】
  • Python模拟试卷2023(1)
  • 常量接口 vs 常量类 vs 枚举区别
  • 第二章 模态命题:必然、可能
  • Selenium 必了解—如何测试REST API
  • pytorch安装老版本
  • 怎么自学电脑编程
  • 【华为OD统一考试B卷 | 100分】斗地主之顺子(C++ Java JavaScript Python)