跳過到頁腳內容
PYTHON 幫助

peewee Python(開發者指南)

Peewee 是一個小巧而富有表現力的ORM ,旨在讓 Python 中的資料庫互動變得輕鬆便捷。 它輕巧易用,並且性能可靠,足以支援複雜的查詢或資料庫模式。 Peewee 支援 SQLite、MySQL 和 PostgreSQL,語法直觀,非常容易學習,因此在學生和專業人士中非常受歡迎。

IronPDF 是一個 Python 庫,可以對 PDF 文件進行完整的端對端操作:建立、讀取、編輯和管理。 使用 Python .NET,可以將 IronPDF 與 Python 應用程式一起使用,從而獲得非常強大的 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 是一個輕量級的、富有表現力的 Python ORM 函式庫,可以輕鬆地與資料庫互動。 它的一些重要特點列舉如下:

-簡單易用: Peewee 提供了一個非常簡單直覺的 API 來對外開放。 開發者可以輕鬆定義具有所有常規屬性的模型,並使用 Python 程式碼輕鬆地與資料庫進行互動。

  • 支援多種資料庫:它支援 SQLite、MySQL、PostgreSQL 和 CockroachDB。

-富有表現力的查詢語法: Peewee 具有簡潔而富有表現力的資料庫查詢語法; 我們可以使用相同的查詢操作,例如 Select、Create、Update 和 delete 查詢,讓開發人員使用 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 在 Python 中運行。 以下步驟將引導您使用 Peewee 建立一個簡單的應用程式來與資料庫交互,並使用 IronPDF 產生 PDF 報告。

什麼是 IronPDF?

IronPDF Python 模組是一個用於建立、編輯和讀取 PDF 的高級庫。 它提供了大量的功能,使程式設計師能夠對 PDF 執行許多可編程活動。 這包括將 HTML 文件轉換為 PDF 文件,以便編輯現有的 PDF 文件。 這將使產生高品質的 PDF 格式報告變得更加靈活和容易。 能夠動態產生和處理 PDF 的程式可以利用這一點。

! peewee Python((工作原理:開發者指南)):圖 3 - IronPDF

HTML 至 PDF 轉換

IronPDF 的功能可以將任何時間的 HTML 資料輕鬆轉換為 PDF 文件。 它還為用戶提供了一個平台,可以直接從線上材料創建極具創新性和引人注目的 PDF 出版物,同時利用 HTML5、CSS3 和 JavaScript 的所有最新功能。

生成和編輯PDF

您甚至可以藉助程式語言產生包含文字、圖片、表格等的新 PDF 文件。 您可以預先開啟準備好的文檔,並使用 IronPDF 對其進行編輯,並添加更多個人化內容。 PDF文件中的任何內容都可以隨時新增、變更或刪除。

複雜的設計與造型

由於 PDF 本身俱有內容樣式,因此可以使用多種字體、顏色和其他設計元素來控制複雜的佈局。 此外,JavaScript 無法用於處理 PDF 中的動態內容,因此無法輕鬆渲染 HTML 內容。

安裝 IronPDF

IronPDF 可以使用 pip 安裝。安裝指令如下圖所示:

pip install ironpdf
pip install ironpdf
SHELL

將 Peewee 與 IronPDF 結合

透過將Peewee ORM的所有階段合併到app.py檔案中,可以建立和設定Peewee ORM,可以插入數據,還可以產生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 的 Python 函式庫 IronPDF 與輕量級 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 輸出

結論

一旦 IronPDF 整合到 Peewee 中,這將為希望管理資料庫和產生動態 PDF 文件的 Python 開發人員提供可靠的選擇。 Peewee 易於使用的 ORM 功能使資料庫互動變得更加容易,開發人員可以非常輕鬆地建立和更改資料庫模式。 另一方面,IronPDF 提供了一個軟體包,可以更輕鬆地將 HTML 內容轉換為高品質的 PDF 報告。

因此,這種組合對於使用從資料庫中檢索的動態資料產生自動報告的應用程式將非常有用。 開發人員可以利用 Peewee 定義模型和執行查詢的便利性,以及 IronPDF 強大的 PDF 創建功能,有效提高效率和生產力。 Peewee 和 IronPDF 結合使用,可以成為靈活且強大的工具,以多種方式滿足 Python 開發領域內各種各樣的應用程式需求。 這些工作可能包括開立發票和撰寫特殊文件的報告。

IronPDF與其他Iron Software產品結合使用,將有助於為客戶提供更優質的軟體解決方案,為使用者提供複雜的解決方案。 這將有利於您簡化專案和流程改善工作。

除了核心功能外,IronPDF 還擁有詳細的文件、活躍的社群和定期的更新週期。 根據前面段落中的信息,開發人員可以將 Iron Software 視為現代軟體開發專案的可靠合作夥伴。 為了幫助開發者了解該程式庫的所有功能,IronPDF 提供免費試用版。 在接下來的幾天裡,您將確保您在許可證費用上花費的$799獲得全部價值。

Curtis Chau
技術作家

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

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