【全栈之路】10 天掌握 Python 开发(9)综合案例

100 阅读3分钟

文件浏览器

任务

ls 命令是 linux 中非常强大的文件查看命令。

请使用 Python 实现一个类似的命令行工具。它需要支持以下命令行选项:

  • -a--all:在文件列表中包括隐藏文件。
  • -w--human-readable:以人类可读格式显示文件大小。
  • -h--help:显示帮助信息。

Python 实现

import os
import argparse
import sys

def ls(directory='.', show_hidden=False, human_readable=False):
    file_list = os.listdir(directory)
    file_list.sort()

    if not show_hidden:
        file_list = [f for f in file_list if not f.startswith('.')]

    if human_readable:
        file_list = [(f, get_human_readable_size(os.path.join(directory, f))) for f in file_list]
        for file, size in file_list:
            print(f"{file}\t{size}")
    else:
        for file in file_list:
            print(file)

def get_human_readable_size(file_path):
    size = os.path.getsize(file_path)
    units = ['B', 'KB', 'MB', 'GB', 'TB']
    index = 0
    while size >= 1024 and index < len(units) - 1:
        size /= 1024
        index += 1
    return f"{size:.2f} {units[index]}"

def main():
    parser = argparse.ArgumentParser(description='List files in a directory.')
    parser.add_argument('-a', '--all', action='store_true', help='Include hidden files')
    parser.add_argument('-w', '--human-readable', action='store_true', help='Display file sizes in human-readable format')
    args = parser.parse_args()

    ls(directory='.', show_hidden=args.all, human_readable=args.human_readable)

if __name__ == '__main__':
    main()

:::tip __main__ 是什么? 在 Python 中,每个 .py 文件都是一个 Python 模块。除了应用程序入口模块之外,其他的模块通常不能直接运行,但为了方便测试,通常会写如下代码为模块提供测试接口:

if __name__ == '__main__':
    main()

这表示,当使用 Python 命令直接运行该脚本时,将执行 main 函数的代码,而当该脚本作为模块被其他模块引用的时候,不会执行 main 函数。 :::

测试

列出文件
python ls.py   
以人类可读格式显示文件大小
python ls.py -w
显示所有文件
python ls.py -a
组合参数
python ls.py -aw

Github 热门

任务

编写一个程序,从 GitHub 网站中获取最近热门的 TOP 50 开源项目。将获取的数据保存到一个 JSON 文件中。

Python 实现

import requests
from bs4 import BeautifulSoup
import json

def get_top_projects():
    url = 'https://github.com/trending'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    project_list = []

    projects = soup.select('article.Box-row')
    for project in projects[:50]:
        project_data = {}
        
        # 获取项目名称
        name_elem = project.select_one('.h3')
        project_data['name'] = name_elem.text.replace(' ','').replace('\n','').strip()

        # 获取项目描述
        desc_elem = project.select_one('p')
        if desc_elem:
            project_data['description'] = desc_elem.text.strip()
        else:
            project_data['description'] = None

        # 获取项目链接
        link_elem = project.select_one('.h3 a')
        project_data['url'] = 'https://github.com' + link_elem['href']

        project_list.append(project_data)

    return project_list

def save_to_json(data, filename):
    with open(filename, 'w') as f:
        json.dump(data, f, indent=4)

if __name__ == '__main__':
    projects = get_top_projects()
    save_to_json(projects, 'top_projects.json')

测试

安装依赖并运行
pip install bs4 requests
python top_50_in_github.py
运行结果
[
    {
        "name": "pytorch-labs/gpt-fast",
        "description": "Simple and efficient pytorch-native transformer text generation in <1000 LOC of python.",
        "url": "https://github.com/pytorch-labs/gpt-fast"
    },
    {
        "name": "dangeng/visual_anagrams",
        "description": "Code for the paper \"Visual Anagrams: Generating Multi-View Optical Illusions with Diffusion Models\"",
        "url": "https://github.com/dangeng/visual_anagrams"
    },
    ...
]

图书商店

任务

实现一个对图书进行管理的书店服务,并提供规范的增删改查 RESTful API。

Python 实现

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 内存数据库
books_db = []
book_id_counter = 0

# 图书模型
class Book(BaseModel):
    id: int
    title: str
    author: str

# 获取所有图书
@app.get("/books")
def get_all_books():
    return books_db

# 获取单个图书
@app.get("/books/{book_id}")
def get_book(book_id: int):
    for book in books_db:
        if book.id == book_id:
            return book
    return {"error": "Book not found"}

# 添加图书
@app.post("/books")
def add_book(title: str, author: str):
    global book_id_counter
    book_id_counter += 1
    book = Book(id=book_id_counter, title=title, author=author)
    books_db.append(book)
    return {"message": "Book added successfully"}

# 更新图书
@app.put("/books/{book_id}")
def update_book(book_id: int, title: str, author: str):
    for book in books_db:
        if book.id == book_id:
            book.title = title
            book.author = author
            return {"message": "Book updated successfully"}
    return {"error": "Book not found"}

# 删除图书
@app.delete("/books/{book_id}")
def delete_book(book_id: int):
    for book in books_db:
        if book.id == book_id:
            books_db.remove(book)
            return {"message": "Book deleted successfully"}
    return {"error": "Book not found"}

测试

安装依赖
pip install fastapi pydantic uvicorn
运行项目
uvicorn main:app --reload --port 8000 # 以 main.py 的 app 作为 Web API 实例
测试接口

FastAPI 会自定生成 Swagger 文档,可访问 http://127.0.0.1:8000/docs 通过 Swagger UI 进行测试。


本书的内容完全免费,开源地址:github.com/luckrnx09/p…