跳過到頁腳內容
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 中将模型创建为类,而得到数据库的所有查询都以 Python 代码进行,这是由于简单的 API。 尽管非常简单,Peewee 仍然非常强大,因为它支持复杂的问题、连接和复杂的关系,并支持连接池。

peewee Python(它如何工作:开发者指南):图 1 - Peewee

灵活性和简约设计使 Peewee 对小项目和更大的应用程序都非常有用,那些应用程序中易用性和快速开发变得至关重要。 用非常少量的样板代码处理复杂的数据库交互,使其成为任何 Python 开发人员的吸引人的 ORM。

Peewee Python 的特性

Peewee 是一个轻量级且富有表现力的 ORM 库,使得在 Python 中与数据库的交互变得简单。 以下列举了它的一些重要特性:

  • 简单易用: Peewee 拥有非常易于使用和直观的 API。 开发人员可以定义所有普通属性的模型,而无需任何麻烦地使用它,并且可以轻松使用 Python 代码与数据库交互。

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

  • 富有表现力的查询语法: Peewee 拥有干净且富有表现力的查询数据库语法; 我们可以使用相同的查询操作如选择、创建、更新和删除查询,使开发人员能够使用 Python 风格的构造编写困难的查询。

  • 模型定义: 一个人在 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 功能,并导入用于生成 PDF 的 IronPDF。 本教程假设您已经具备 Python 的知识,并了解如何通过 Python .NET 设置 IronPDF 以在 Python 中使用,以及如何使用 Peewee。 以下步骤将引导您创建一个简单的应用程序,使用 Peewee 与数据库交互,并使用 IronPDF 生成 PDF 报告。

什麼是 IronPDF?

IronPDF Python 模块是一个用于创建、编辑和读取 PDF 的高级库。 它提供了大量功能,使程序员可以使用 PDF 执行许多可编程的活动。 这包括将 HTML 文件转换为 PDF 文件,以便编辑现有的 PDF。 这将使生成 PDF 格式的精彩报告更加灵活和容易。 动态生成和处理 PDF 的程序可以利用这一点。

peewee Python(它如何工作:开发者指南):图 3 - IronPDF

HTML 到 PDF 轉換

任何时间上传的 HTML 数据可以轻松通过 IronPDF 转换为 PDF 文档。 它进一步为用户提供了一个平台,可以直接从在线材料创建极具创意和吸引力的 PDF 出版物,同时利用所有最新的 HTML5、CSS3 和 JavaScript 功能。

生成和编辑 PDFs

您可以使用编程语言生成带有文本、图片、表格等的新的 PDF 文档。 您可以提前打开准备好的文档并使用 IronPDF 编辑它们,添加额外个性化。 PDF 文档中的任何内容都可以随时添加、修改或移除。

复杂的设计和样式

由于其固有的 PDF 内容风格,复杂的布局可以通过多种字体、颜色和其他设计元素进行控制,这使其成为可能。 此外,JavaScript 不可应用于处理 PDF 中的动态材料,以便于 HTML 内容的渲染。

安装 IronPDF

IronPDF 可通过 Pip 安装。 安装命令如下所示:

pip install ironpdf
pip install ironpdf
SHELL

将 Peewee 和 IronPDF 结合在一起

Peewee ORM 可以创建和配置,数据可以插入,并通过将所有阶段结合到 app.py 文件中生成 PDF 报告。

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 = """
    <html>
    <head><title>Data Report</title></head>
    <body>
        <h1>User Data Report</h1>
        <h2>Users</h2>
        <ul>
    """
    for user in users:
        html_content += f"<li>{user.username}, Age: {user.age}</li>"
    html_content += "</ul><h2>Tweets</h2><ul>"
    for tweet in tweets:
        html_content += f"<li>{tweet.user.username} tweeted: {tweet.content}</li>"
    html_content += "</ul></body></html>"

    # 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
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 = """
    <html>
    <head><title>Data Report</title></head>
    <body>
        <h1>User Data Report</h1>
        <h2>Users</h2>
        <ul>
    """
    for user in users:
        html_content += f"<li>{user.username}, Age: {user.age}</li>"
    html_content += "</ul><h2>Tweets</h2><ul>"
    for tweet in tweets:
        html_content += f"<li>{tweet.user.username} tweeted: {tweet.content}</li>"
    html_content += "</ul></body></html>"

    # 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

此代码展示了如何使用 Python .NET 将为 PDF 创建的 IronPDF Python 库与 Python 中的轻量级 ORM Peewee 结合在一起。 使用 Peewee,它首先创建一个 SQLite 数据库并定义 User 和 Tweet 模型及其相关字段。 创建数据库表后,将示例数据添加到其中。 然后,使用 IronPDF 的 ChromePdfRenderer 类,generate_pdf 函数检索这些数据并将其转换为 HTML 字符串,然后被渲染为 PDF。

peewee Python(它如何工作:开发者指南):图 4 - 控制台输出

PDF 存储在当前工作目录中。 利用 Peewee 进行数据库管理的优势以及使用 IronPDF 生成精美的PDF 文档,此配置在 Python 应用程序中实现了流畅的数据库交互和自动 PDF 报告输出。

peewee Python(它如何工作:开发者指南):图 5 - PDF 输出

結論

这将为希望管理数据库并生成动态 PDF 文档的 Python 开发人员提供可靠的解决方案,一旦 IronPDF 集成到 Peewee 中。 使用简单易用的 ORM 功能,在 Peewee 中使数据库交互变得更简单,允许开发人员轻松地构建和更改数据库方案。 另一方面,IronPDF 提供了一个便于将 HTML 内容翻译为高质量 PDF 报告的包。

因此,这种组合在生成使用从数据库中检索的动态数据生成自动化报告的应用程序中将非常有用。 开发人员可以利用 Peewee 轻松定义模型和执行查询,而 IronPDF 强大的 PDF 创建功能,来有效地提高效率和生产力。 Peewee 和 IronPDF 作为一个组合,成为灵活而强大的工具来应对 Python 开发界内各种应用需求。 这些应用可能从开票到特别文档的报告不等。

Combining IronPDF with other Iron Software products will help give superior software solutions to clients that offer complex solutions to users. 这将为您自己简化提高项目和过程总体操作的任务。

除了核心功能外,IronPDF 还拥有详细文档、活跃的社区和定期更新周期。 基于前面段落中的信息,开发人员可以将 Iron Software 视为现代软件开发项目的可靠合作伙伴。 为了解这库的所有功能,IronPDF 为开发人员提供了免费试用。 在接下来的日子里,您将确保对您在许可费用上花费的 $799 得到充分的价值。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。