溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Python如何使用Rich?type和TinyDB構(gòu)建聯(lián)系人通訊錄

發(fā)布時(shí)間:2022-08-09 09:30:45 來(lái)源:億速云 閱讀:125 作者:iii 欄目:開(kāi)發(fā)技術(shù)

今天小編給大家分享一下Python如何使用Rich type和TinyDB構(gòu)建聯(lián)系人通訊錄的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

引言

我們將學(xué)習(xí)如何構(gòu)建一個(gè)終端應(yīng)用程序(CLI應(yīng)用程序)來(lái)管理我們的通訊錄

我們將使用type來(lái)構(gòu)建CLI應(yīng)用程序,使用Rich來(lái)創(chuàng)建彩色終端輸出,使用TinyDB來(lái)創(chuàng)建數(shù)據(jù)庫(kù)。

工具準(zhǔn)備

我們將在這個(gè)項(xiàng)目中使用一些外部庫(kù)。讓我們來(lái)了解一下,并逐一安裝。 但是在我們安裝之前,讓我們創(chuàng)建一個(gè)虛擬環(huán)境并激活它。 我們將使用 virtualenv 創(chuàng)建一個(gè)虛擬環(huán)境。Python現(xiàn)在附帶了一個(gè)預(yù)先安裝的virtualenv庫(kù)。因此,要?jiǎng)?chuàng)建一個(gè)虛擬環(huán)境,你可以使用下面的命令:

python -m venv env

上面的命令將創(chuàng)建一個(gè)名為env的虛擬環(huán)境?,F(xiàn)在,我們需要使用下面的命令來(lái)激活環(huán)境:

. env/Scripts/activate

要驗(yàn)證環(huán)境是否已被激活,可以在終端中看到(env)?,F(xiàn)在,我們可以安裝庫(kù)了。

Rich是一個(gè)Python庫(kù),用于向終端編寫(xiě)富文本(帶有顏色和樣式),并用于顯示高級(jí)內(nèi)容,如表、標(biāo)記和語(yǔ)法高亮顯示代碼。

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

pip install Rich

Typer是一個(gè)用于構(gòu)建CLI應(yīng)用程序的庫(kù)。

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

pip install Typer

TinyDB是一個(gè)純Python編寫(xiě)的面向文檔的數(shù)據(jù)庫(kù),沒(méi)有外部依賴(lài)。

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

pip install TinyDB

通訊錄特征

我們的通訊錄應(yīng)用程序?qū)⑹且粋€(gè)基于終端的應(yīng)用程序。類(lèi)似于Todo應(yīng)用程序,我們可以對(duì)其執(zhí)行以下操作:

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.

如何創(chuàng)建聯(lián)系人模型

首先,我們將為Contact創(chuàng)建一個(gè)自定義類(lèi)或模型。想想接觸應(yīng)該包含的所有領(lǐng)域。 我能想到這些字段——姓名和聯(lián)系電話(huà)。如果您能想到更多,可以將它們添加到您的模型中。我們現(xiàn)在要繼續(xù)調(diào)查這兩位。 創(chuàng)建一個(gè)名為contact_book的目錄。在其中,創(chuàng)建一個(gè)名為model.py的Python文件。在文件中增加如下內(nèi)容:

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})"

我們創(chuàng)建了一個(gè)名為Contact的類(lèi),它接受兩個(gè)強(qiáng)制參數(shù):name和contact_number。

除了這兩個(gè)參數(shù)外,它還接受三個(gè)可選參數(shù):position、date_created和date_updated。如果沒(méi)有傳遞這三個(gè)可選參數(shù),它們將分別默認(rèn)為當(dāng)前索引和當(dāng)前時(shí)間。

此外,我們還定義了repr方法,該方法以更易于閱讀的方式返回對(duì)象。

如何使用TinyDB創(chuàng)建數(shù)據(jù)庫(kù)

現(xiàn)在,讓我們?cè)O(shè)置TinyDB并創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)

在contact_book目錄中,創(chuàng)建一個(gè)init.py文件,并添加以下內(nèi)容:

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

我們已經(jīng)創(chuàng)建了TinyDB類(lèi)的一個(gè)實(shí)例,并將文件名傳遞給它。這將創(chuàng)建一個(gè)JSON文件通訊錄。Json,我們的數(shù)據(jù)將被存儲(chǔ)。要從這個(gè)數(shù)據(jù)庫(kù)檢索數(shù)據(jù),我們需要一個(gè)tinydb庫(kù)中Query類(lèi)的實(shí)例。

現(xiàn)在,讓我們定義將用于與數(shù)據(jù)庫(kù)交互的不同函數(shù)。在contact_book目錄中,創(chuàng)建一個(gè)database.py文件,并在其中添加以下內(nèi)容:

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)

我們定義了四個(gè)不同的函數(shù)——create()、read()、update()和delete()用于上面提到的每個(gè)操作。我們使用position屬性來(lái)識(shí)別特定的聯(lián)系人。change_position()函數(shù)負(fù)責(zé)在刪除聯(lián)系人時(shí)保持聯(lián)系人的位置。

如何使用typer創(chuàng)建命令行

現(xiàn)在讓我們使用type創(chuàng)建CLI。在contact_book目錄之外,創(chuàng)建一個(gè)main.py文件,并添加以下內(nèi)容。如何使用type創(chuàng)建命令行

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()

首先,我們從類(lèi)型庫(kù)中創(chuàng)建Typer類(lèi)的一個(gè)實(shí)例。然后,我們?yōu)樯厦嬗懻摰乃膫€(gè)操作創(chuàng)建四個(gè)單獨(dú)的函數(shù)。我們使用@app.command()裝飾器將每個(gè)函數(shù)綁定到一個(gè)命令中。我們還添加了short_help來(lái)幫助用戶(hù)使用命令。

要添加聯(lián)系人,我們需要name和contact_number參數(shù)。為了展示隱形人,我們什么都不需要。要編輯聯(lián)系人,我們肯定需要位置,而name和contact_number參數(shù)是可選的。要移除接觸點(diǎn),我們只需要位置。

目前,我們沒(méi)有在方法內(nèi)部進(jìn)行任何操作。我們只是使用typing類(lèi)中的echo方法進(jìn)行打印。在main方法中,我們只需要調(diào)用app()對(duì)象。

如果你運(yùn)行這個(gè)應(yīng)用程序,你會(huì)得到一個(gè)類(lèi)似的輸出:

Python如何使用Rich?type和TinyDB構(gòu)建聯(lián)系人通訊錄

如何使用Rich設(shè)計(jì)終端

我們希望在一個(gè)漂亮的表格布局中使用不同的顏色顯示聯(lián)系人。Rich 可以幫我們。

現(xiàn)在讓我們修改main.py中的show()函數(shù),因?yàn)樗?fù)責(zé)在終端上打印聯(lián)系人。

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_, show_lines=True)
        table.add_column("#", , 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)

我們首先創(chuàng)建了Console類(lèi)的一個(gè)實(shí)例。在show()方法中,我們現(xiàn)在有一個(gè)虛擬的聯(lián)系人列表。使用console對(duì)象,我們用粗體紅色打印標(biāo)題。

接下來(lái),我們創(chuàng)建一個(gè)表并添加列。現(xiàn)在,我們對(duì)聯(lián)系人進(jìn)行迭代,并將它們作為不同顏色的單獨(dú)行放入表中。最后,我們打印表格。

如何使用打字命令連接數(shù)據(jù)庫(kù)操作

現(xiàn)在,讓我們進(jìn)行最后一步,將數(shù)據(jù)庫(kù)操作與命令連接起來(lái)。也就是說(shuō),當(dāng)我們運(yùn)行一個(gè)命令時(shí),它應(yīng)該與數(shù)據(jù)庫(kù)進(jìn)行適當(dāng)?shù)慕换ァ?/p>

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_, show_lines=True)
        table.add_column("#", , 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()

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

以上就是“Python如何使用Rich type和TinyDB構(gòu)建聯(lián)系人通訊錄”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI