跳至页脚内容
PYTHON 帮助

peewee Python((如何运作:开发人员指南))

Peewee 是一个小型、富有表现力的ORM,旨在使与 Python 中的数据库交互变得容易。 它轻量级、易于使用,并且有足够的信心支持复杂的查询或数据库模式。 Peewee 支持 SQLite、MySQL 和 PostgreSQL,具有直观的语法,非常易于学习,因此在学生和专业人士中非常受欢迎。

IronPDF 是一个 Python 库,可以实现与 PDF 文档的完整端到端工作:创建、读取、编辑和管理。 使用 Python .NET,可以在 Python 应用程序中使用 IronPDF,从而获得非常强大的 PDF 生成能力。 因此,这种组合在生成基于从数据库检索的数据的 PDF 报告方面非常有用。

这种集成将 Peewee 与 IronPDF 结合在一起,让 Python 开发人员在创建应用程序时,能够高效管理和查询数据库,同时能够生成动态、数据驱动的 PDF 文档。 这种组合使得从数据检索到报告生成的完美工作流程成为可能,从而提供了一组非常强大的工具集,用于创建专业和自动化文档。 无论是从简单的商业报告,如发票,到复杂的报告,Peewee 和 IronPDF 一起都为任何 Python 应用程序中的数据库驱动的 PDF 生成提供了一个完美的解决方案。

什么是 Peewee Python?

Peewee 是一个小型的、富有表现力的 Python ORM,用于简化与数据库的工作。 它可以轻松创建模型,并让常见的查询如搜索、添加、更新和删除多个记录在数据库中变得简单。 Peewee 可以在许多不同的使用场景中使用,原因是它支持不同的后端:SQLite、MySQL 和 PostgreSQL。

Peewee 简单易用是它的一个亮点。 开发人员可以很容易地在 Python 中将模型定义为类,而所有对数据库的查询都可以通过简单的 API 作为 Python 代码执行。 尽管如此简单,Peewee 仍然非常强大,因为它支持复杂的问题、连接和复杂的关系,并支持连接池。

peewee Python(它是如何工作的:开发人员指南):图 1 - Peewee

灵活性和极简设计使 Peewee 对于需要易用性和快速开发的小项目和较大型应用程序非常有用。 处理复杂的数据库交互只需很少的样板代码,使其成为任何 Python 开发人员都很有吸引力的 ORM。

Peewee Python 的功能

Peewee 是一个轻量级的、富有表现力的 Python ORM 库,用于轻松与数据库交互。 其中一些重要功能如下所列:

  • 简单易用: Peewee 具有非常简单直观的 API。 开发人员可以毫不费力地定义具有所有正常属性的模型,并轻松地使用 Python 代码与数据库交互。

  • 多数据库支持: 它支持 SQLite、MySQL、PostgreSQL 和 CockroachDB。

  • 富有表现力的查询语法: Peewee 拥有干净富有表现力的查询数据库的语法; 我们可以使用 Select、Create、Update 和删除查询等相同的查询操作,让开发人员使用 Pythonic 结构编写复杂的查询。

  • 模型定义: 在 Peewee 中数据库模型被定义为 Python 类。 类上的字段与数据库列匹配。 这种定义确保如果有人更改数据库模式,Python 代码也进行了相应的更改,反之亦然。

  • 关系: 它支持包括外键、一对一和多对多关系在内的所有关系,这在建模复杂数据中是必需的。

  • 连接池: Peewee 自带连接池,通过重用数据库连接提高性能。

  • 事务: 原子事务确保一组数据库操作得以执行,但如果其中任何一个操作失败,则所有操作都将回滚以保持数据的有效性。

  • 信号和钩子: Peewee 提供了用于在某些事件之前或之后实现自定义行为(如保存或删除记录)的信号和钩子。

  • 迁移: 此外,这使 Peewee-migrate 等第三方库与主库集成,并因此管理数据库模式迁移。 这将有助于数据库版本的平稳过渡。

  • 可扩展性: Peewee 可以通过自定义字段、查询或根据具体应用需求的其他一些功能轻松扩展。

  • Playhouse 扩展: 此模块附带了 Playhouse 的各种扩展,包括 SQLite 的全文搜索、一些 PostgreSQL 特定功能和一些管理连接的工具。

  • 异步支持: aiopeewee 是一个扩展,使 Peewee 支持异步操作,适合高性能应用程序。

创建和配置 Peewee

以下步骤可以帮助您在任何 Python 项目中开始使用 Peewee,设置一个使用 Peewee ORM 的简单应用程序。

安装 Peewee

首先,使用 pip 安装 Peewee:

pip install peewee
pip install peewee
SHELL

定义您的模型

请确保在名为 app.py 的 Python 文件中定义您的数据库模型。 在这里,我们将简单地使用 SQLite。

from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField

# Define the database connection
db = SqliteDatabase('my_database.db')

# Define a base model class
class BaseModel(Model):
    class Meta:
        database = db

# Define a User model
class User(BaseModel):
    username = CharField(unique=True)
    age = IntegerField()

# Define a Tweet model, which is related to the User model
class Tweet(BaseModel):
    user = ForeignKeyField(User, backref='tweets')
    content = CharField()

# Create the tables
db.connect()
db.create_tables([User, Tweet])
from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField

# Define the database connection
db = SqliteDatabase('my_database.db')

# Define a base model class
class BaseModel(Model):
    class Meta:
        database = db

# Define a User model
class User(BaseModel):
    username = CharField(unique=True)
    age = IntegerField()

# Define a Tweet model, which is related to the User model
class Tweet(BaseModel):
    user = ForeignKeyField(User, backref='tweets')
    content = CharField()

# Create the tables
db.connect()
db.create_tables([User, Tweet])
PYTHON

插入数据

现在让我们向我们的数据库添加一些数据。

def insert_data():
    # Insert a new user
    alice = User.create(username='Alice', age=30)
    # Insert some tweets for Alice
    Tweet.create(user=alice, content='Hello world!')
    Tweet.create(user=alice, content='I love Peewee!')
    # Insert another user and a tweet for that user
    bob = User.create(username='Bob', age=25)
    Tweet.create(user=bob, content='This is Bob')

insert_data()
def insert_data():
    # Insert a new user
    alice = User.create(username='Alice', age=30)
    # Insert some tweets for Alice
    Tweet.create(user=alice, content='Hello world!')
    Tweet.create(user=alice, content='I love Peewee!')
    # Insert another user and a tweet for that user
    bob = User.create(username='Bob', age=25)
    Tweet.create(user=bob, content='This is Bob')

insert_data()
PYTHON

查询数据

现在,让我们构造一些代码来从我们的数据库中提取所有这些信息。

def query_data():
    # Query to select all users and print their usernames and ages
    for user in User.select():
        print(f'User: {user.username}, Age: {user.age}')

    # Find tweets for a specific user, in this case, 'Alice'
    for tweet in Tweet.select().join(User).where(User.username == 'Alice'):
        print(f'{tweet.user.username} tweeted: {tweet.content}')

query_data()
def query_data():
    # Query to select all users and print their usernames and ages
    for user in User.select():
        print(f'User: {user.username}, Age: {user.age}')

    # Find tweets for a specific user, in this case, 'Alice'
    for tweet in Tweet.select().join(User).where(User.username == 'Alice'):
        print(f'{tweet.user.username} tweeted: {tweet.content}')

query_data()
PYTHON

以下是上述所有代码的综合截图。

peewee Python(它是如何工作的:开发人员指南):图 2 - 查询数据输出

开始

首先,你需要导入 Peewee 以获得与对象关系映射相关的功能,并使用 IronPDF 生成 PDF。 本教程假设您已经了解 Python 以及如何通过 Python .NET 和 Peewee 设置 IronPDF。 以下步骤将引导您创建一个使用 Peewee 交互数据库的简单应用程序,而 IronPDF 将用于生成 PDF 报告。

什么是 IronPDF? [IronPDF](https://ironpdf.com/python/) Python 模块是一个高级库,用于创建、编辑和读取 PDF。 它提供了大量功能,程序员可以用 PDF 执行许多可编程活动。 这包括将 HTML 文件转换为 PDF 文件以编辑现有 PDF。 这将使它更加灵活并更容易生成出色的 PDF 格式报告。 动态生成和处理 PDF 的程序可以利用这一点。 ![peewee Python(它是如何工作的:开发人员指南):图 3 - IronPDF](/static-assets/pdf/blog/peewee-python/peewee-python-3.webp) #### HTML 至 PDF 转换 任何 HTML 数据,无论何时更新,都可以通过 IronPDF 的功能轻松转换为 PDF 文档。 它还为用户提供了一个平台,可以直接从在线材料创建极具创新性和吸引力的 PDF 出版物,同时利用 HTML5、CSS3 和 JavaScript 的所有最新功能。 #### 生成和编辑 PDF 你可以使用编程语言生成带有文本、图像、表格等的新 PDF 文档。 你可以提前打开准备好的文档,并通过 IronPDF 进行编辑,进一步个性化。 PDF 文档的任何内容都可以随时添加、更改或删除。 #### 复杂的设计和样式 由于它本身具有 PDF 的内容样式,因此可以使用多种字体、颜色和其他设计元素控制复杂的布局。 此外,JavaScript 不能用于处理 PDF 中的动态材料以便于呈现 HTML 内容。 #### 安装 IronPDF IronPDF 可以通过 Pip 安装。安装命令如下所示: ```bash pip install ironpdf ``` ## 将 Peewee 与 IronPDF 结合使用 可以创建和配置 Peewee ORM,插入数据,并通过将所有阶段结合到 app.py 文件中生成 PDF 报告。 ```python from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField import os from ironpdf import * # Import IronPDF for PDF generation import warnings # Suppress any warning messages for clean output warnings.filterwarnings('ignore') # You must specify your license key if IronPDF requires it; use an empty string for trial License.LicenseKey = "" # Define the database connection using SQLite db = SqliteDatabase('my_database.db') # BaseModel class that will define common configurations for all models class BaseModel(Model): class Meta: database = db # Define a User model to interact with the 'User' table in the database class User(BaseModel): username = CharField(unique=True) # Ensure username is unique age = IntegerField() # Define a Tweet model for the 'Tweet' table that references User class Tweet(BaseModel): user = ForeignKeyField(User, backref='tweets') # Define relationship with User content = CharField() # Connect to the database and create the necessary tables if they don't exist db.connect() db.create_tables([User, Tweet]) def insert_data(): # Insert some sample data into the User and Tweet models alice = User.create(username='Alice', age=30) Tweet.create(user=alice, content='Hello world!') Tweet.create(user=alice, content='I love Peewee!') bob = User.create(username='Bob', age=25) Tweet.create(user=bob, content='This is Bob') def generate_pdf(): # Fetch the data from the database users = User.select() tweets = Tweet.select().join(User) # Prepare HTML content for the PDF generation html_content = """ Data Report

User Data Report

Users

    """ for user in users: html_content += f"
  • {user.username}, Age: {user.age}
  • " html_content += "

Tweets

    " for tweet in tweets: html_content += f"
  • {tweet.user.username} tweeted: {tweet.content}
  • " html_content += "
" # Create a PDF document using IronPDF renderer = ChromePdfRenderer() pdf = renderer.RenderHtmlAsPdf(html_content) # Save the PDF file to the current working directory output_path = os.path.join(os.getcwd(), "Data_Report.pdf") pdf.SaveAs(output_path) print(f"PDF Report saved to {output_path}") if __name__ == '__main__': insert_data() # Insert data into the database generate_pdf() # Generate a PDF report based on the data ``` 这段代码展示了如何使用 Python .NET 将用于 PDF 创建的 Python 库 IronPDF 与轻量级 Python ORM Peewee 相结合。 使用 Peewee,它首先创建了一个 SQLite 数据库,并使用适当的字段定义了用户和推文模型。 在创建数据库表之后,将样本数据添加到它们中。 然后,使用 IronPDF 的 ChromePdfRenderer 类,`generate_pdf` 函数检索此数据,并将其转换为 HTML 字符串,然后作为 PDF 呈现。 ![peewee Python(它是如何工作的:开发人员指南):图 4 - 控制台输出](/static-assets/pdf/blog/peewee-python/peewee-python-4.webp) PDF 存储在当前工作目录中。 利用 Peewee 的数据库管理优势和 IronPDF 生成精美的[PDF 文档](https://ironpdf.com/python/docs/)的好处,此配置在 Python 应用程序中实现了流畅的数据库交互和自动 PDF 报告输出。 ![peewee Python(它是如何工作的:开发人员指南):图 5 - PDF 输出](/static-assets/pdf/blog/peewee-python/peewee-python-5.webp) ## 结论 一旦 IronPDF 集成到 Peewee 中,这将为希望管理数据库和生成动态 PDF 文档的 Python 开发人员提供可靠的选择。 通过易于使用的 ORM 功能,在 Peewee 中数据库交互变得更加容易,让开发人员能够轻松构建和更改数据库方案。 另一方面,IronPDF 包含一个包,使得将 HTML 内容转换为优质的 PDF 报告变得更加容易。 因此,此组合在生成使用从数据库检索的动态数据的自动报告的应用程序中非常有用。 开发人员可以利用 Peewee 的方便模型定义和查询执行,与 IronPDF 的强大 PDF 创建功能,有效增强效率和生产力。 Peewee 和 IronPDF 作为一个组合,成为灵活和强大的工具,以多种方式在 Python 开发宇宙中满足各种应用程序需求。 这些可能范围从开发票到特殊文档的报告。 Combining [IronPDF](licensing) with other [Iron Software](/) products will help give superior software solutions to clients that offer complex solutions to users. 这将对你有好处,简化增强项目操作和总体程序的任务。 除了核心功能之外,IronPDF 还提供详细的文档、活跃的社区和定期的更新周期。 根据上面段落中的信息,开发人员可以认为 Iron Software 是现代软件开发项目的可靠合作伙伴。 要了解此库的所有功能,IronPDF 为开发人员提供了免费试用。 在接下来的日子里,您将确保完全获得$liteLicense花费在许可证费用上的价值。
Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。