Python使用Rich type和TinyDB構建聯系人通訊錄

引言

我們將學習如何構建一個終端應用程序(CLI應用程序)來管理我們的通訊錄

我們將使用type來構建CLI應用程序,使用Rich來創建彩色終端輸出,使用TinyDB來創建數據庫。

工具準備

我們將在這個項目中使用一些外部庫。讓我們來瞭解一下,並逐一安裝。 但是在我們安裝之前,讓我們創建一個虛擬環境並激活它。 我們將使用 virtualenv 創建一個虛擬環境。Python現在附帶瞭一個預先安裝的virtualenv庫。因此,要創建一個虛擬環境,你可以使用下面的命令:

python -m venv env

上面的命令將創建一個名為env的虛擬環境。現在,我們需要使用下面的命令來激活環境:

. env/Scripts/activate

要驗證環境是否已被激活,可以在終端中看到(env)。現在,我們可以安裝庫瞭。

Rich是一個Python庫,用於向終端編寫富文本(帶有顏色和樣式),並用於顯示高級內容,如表、標記和語法高亮顯示代碼。

要安裝Rich,使用以下命令:

pip install Rich

Typer是一個用於構建CLI應用程序的庫。

要安裝Typer,使用以下命令:

pip install Typer

TinyDB是一個純Python編寫的面向文檔的數據庫,沒有外部依賴。

要安裝TinyDB,使用下面的命令:

pip install TinyDB

通訊錄特征

我們的通訊錄應用程序將是一個基於終端的應用程序。類似於Todo應用程序,我們可以對其執行以下操作:

Add (or Create) : You can add a new contact in the contact book.

Show (or Read) : You can see all your contacts saved in the contact book.

Edit (or Update) : You can edit the contacts saved in the contact book.

Remove (or Delete) : You can delete the contacts saved in the contact book.

如何創建聯系人模型

首先,我們將為Contact創建一個自定義類或模型。想想接觸應該包含的所有領域。 我能想到這些字段——姓名和聯系電話。如果您能想到更多,可以將它們添加到您的模型中。我們現在要繼續調查這兩位。 創建一個名為contact_book的目錄。在其中,創建一個名為model.py的Python文件。在文件中增加如下內容:

import datetime
class Contact:
    def __init__ (self, name, contact_number, position=None, date_created=None, date_updated=None):
        self.name = name
        self.contact_number = contact_number
        self.position = position
        self.date_created = date_created if date_created is not None else datetime.datetime.now().isoformat()
        self.date_updated = date_updated if date_updated is not None else datetime.datetime.now().isoformat()
    def __repr__ (self) -> str:
        return f"({self.name}, {self.contact_number}, {self.position}, {self.date_created}, {self.date_updated})"

我們創建瞭一個名為Contact的類,它接受兩個強制參數:name和contact_number。

除瞭這兩個參數外,它還接受三個可選參數:position、date_created和date_updated。如果沒有傳遞這三個可選參數,它們將分別默認為當前索引和當前時間。

此外,我們還定義瞭repr方法,該方法以更易於閱讀的方式返回對象。

如何使用TinyDB創建數據庫

現在,讓我們設置TinyDB並創建一個數據庫

在contact_book目錄中,創建一個init.py文件,並添加以下內容:

from tinydb import TinyDB, Query
db = TinyDB('contact-book.json')
db.default_table_name = 'contact-book'
ContactQuery = Query()

我們已經創建瞭TinyDB類的一個實例,並將文件名傳遞給它。這將創建一個JSON文件通訊錄。Json,我們的數據將被存儲。要從這個數據庫檢索數據,我們需要一個tinydb庫中Query類的實例。

現在,讓我們定義將用於與數據庫交互的不同函數。在contact_book目錄中,創建一個database.py文件,並在其中添加以下內容:

from typing import List
import datetime
from contact_book.model import Contact
from contact_book import db, ContactQuery
def create(contact: Contact) -> None:
    contact.position = len(db)+1
    new_contact = {
        'name': contact.name,
        'contact_number': contact.contact_number,
        'position': contact.position,
        'date_created': contact.date_created,
        'date_updated': contact.date_updated
    }
    db.insert(new_contact)
def read() -> List[Contact]:
    results = db.all()
    contacts = []
    for result in results:
        new_contact = Contact(result['name'], result['contact_number'], result['position'],
                              result['date_created'], result['date_updated'])
        contacts.append(new_contact)
    return contacts
def update(position: int, name: str, contact_number: str) -> None:
    if name is not None and contact_number is not None:
        db.update({'name': name, 'contact_number': contact_number},
                  ContactQuery.position == position)
    elif name is not None:
        db.update({'name': name}, ContactQuery.position == position)
    elif contact_number is not None:
        db.update({'contact_number': contact_number},
                  ContactQuery.position == position)
def delete(position) -> None:
    count = len(db)
    db.remove(ContactQuery.position == position)
    for pos in range(position+1, count):
        change_position(pos, pos-1)
def change_position(old_position: int, new_position: int) -> None:
    db.update({'position': new_position},
              ContactQuery.position == old_position)

我們定義瞭四個不同的函數——create()、read()、update()和delete()用於上面提到的每個操作。我們使用position屬性來識別特定的聯系人。change_position()函數負責在刪除聯系人時保持聯系人的位置。

如何使用typer創建命令行

現在讓我們使用type創建CLI。在contact_book目錄之外,創建一個main.py文件,並添加以下內容。如何使用type創建命令行

import typer
app = typer.Typer()
@app.command(short_help='adds a contact')
def add(name: str, contact_number: str):
    typer.echo(f"Adding {name}, {contact_number}")
@app.command(short_help='shows all contacts')
def show():
    typer.echo(f"All Contacts")
@app.command(short_help='edits a contact')
def edit(position: int, name: str = None, contact_number: str = None):
    typer.echo(f"Editing {position}")
@app.command(short_help='removes a contact')
def remove(position: int):
    typer.echo(f"Removing {position}")
if __name__ == " __main__":
    app()

首先,我們從類型庫中創建Typer類的一個實例。然後,我們為上面討論的四個操作創建四個單獨的函數。我們使用@app.command()裝飾器將每個函數綁定到一個命令中。我們還添加瞭short_help來幫助用戶使用命令。

要添加聯系人,我們需要name和contact_number參數。為瞭展示隱形人,我們什麼都不需要。要編輯聯系人,我們肯定需要位置,而name和contact_number參數是可選的。要移除接觸點,我們隻需要位置。

目前,我們沒有在方法內部進行任何操作。我們隻是使用typing類中的echo方法進行打印。在main方法中,我們隻需要調用app()對象。

如果你運行這個應用程序,你會得到一個類似的輸出:

如何使用Rich設計終端

我們希望在一個漂亮的表格佈局中使用不同的顏色顯示聯系人。Rich 可以幫我們。

現在讓我們修改main.py中的show()函數,因為它負責在終端上打印聯系人。

from rich.console import Console
from rich.table import Table
console = Console()
@app.command(short_help='shows all contacts')
def show():
    contacts = [("Ashutosh Krishna", "+91 1234554321"),
                ("Bobby Kumar", "+91 9876556789")]
    console.print("[bold magenta]Contact Book[/bold magenta]", "📕")
    if len(contacts) == 0:
        console.print("[bold red]No contacts to show[/bold red]")
    else:
        table = Table(show_header=True, header_style="bold blue", show_lines=True)
        table.add_column("#", style="dim", width=3, justify="center")
        table.add_column("Name", min_width=20, justify="center")
        table.add_column("Contact Number", min_width=12, justify="center")
        for idx, contact in enumerate(contacts, start=1):
            table.add_row(str(idx), f'[cyan]{contact[0]}[/cyan]', f'[green]{contact[1]}[/green]')
        console.print(table)

我們首先創建瞭Console類的一個實例。在show()方法中,我們現在有一個虛擬的聯系人列表。使用console對象,我們用粗體紅色打印標題。

接下來,我們創建一個表並添加列。現在,我們對聯系人進行迭代,並將它們作為不同顏色的單獨行放入表中。最後,我們打印表格。

如何使用打字命令連接數據庫操作

現在,讓我們進行最後一步,將數據庫操作與命令連接起來。也就是說,當我們運行一個命令時,它應該與數據庫進行適當的交互。

import typer
from rich.console import Console
from rich.table import Table
from contact_book.model import Contact
from contact_book.database import create, read, update, delete
app = typer.Typer()
console = Console()
@app.command(short_help='adds a contact')
def add(name: str, contact_number: str):
    typer.echo(f"Adding {name}, {contact_number}")
    contact = Contact(name, contact_number)
    create(contact)
    show()
@app.command(short_help='shows all contacts')
def show():
    contacts = read()
    console.print("[bold magenta]Contact Book[/bold magenta]", "📕")
    if len(contacts) == 0:
        console.print("[bold red]No contacts to show[/bold red]")
    else:
        table = Table(show_header=True,
                      header_style="bold blue", show_lines=True)
        table.add_column("#", style="dim", width=3, justify="center")
        table.add_column("Name", min_width=20, justify="center")
        table.add_column("Contact Number", min_width=12, justify="center")
        for idx, contact in enumerate(contacts, start=1):
            table.add_row(str(
                idx), f'[cyan]{contact.name}[/cyan]', f'[green]{contact.contact_number}[/green]')
        console.print(table)
@app.command(short_help='edits a contact')
def edit(position: int, name: str = None, contact_number: str = None):
    typer.echo(f"Editing {position}")
    update(position, name, contact_number)
    show()
@app.command(short_help='removes a contact')
def remove(position: int):
    typer.echo(f"Removing {position}")
    delete(position)
    show()
if __name__ == " __main__":
    app()

在上面的代碼中,我們使用瞭前面創建的create()、read()、update()和delete()。

以上就是Python使用Rich type和TinyDB構建聯系人通訊錄應用程序的詳細內容,更多關於Python構建通訊錄的資料請關註WalkonNet其它相關文章!

推薦閱讀: