百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python进阶-day28-30:综合项目

off999 2025-05-21 15:45 26 浏览 0 评论

项目概述:任务管理器

功能

  • 用户可以创建、查看、更新和删除任务。
  • 每个任务包含标题、描述、优先级、截止日期和状态(待办/已完成)。
  • 使用SQLite存储任务数据。
  • 通过第三方API(例如天气API)为任务提供额外信息(例如,提醒用户某天任务所在地的天气)。
  • 提供命令行界面(CLI)或简单的Flask Web界面。
  • 包含单元测试和详细文档。

技术栈

  • Python: 核心语言
  • OOP: 类和对象设计
  • SQLite: 轻量级数据库
  • Requests: 调用外部API(天气API)
  • Flask(可选):Web界面
  • unittest: 单元测试
  • GitHub: 代码托管
  • README: 项目文档

Day 28: 项目设计与核心功能实现

1. 确定项目结构

创建一个清晰的目录结构,方便组织代码:

todo_manager/
├── src/
│   ├── __init__.py
│   ├── task.py           # 任务类(OOP)
│   ├── database.py       # 数据库操作
│   ├── api.py            # API调用
│   ├── cli.py            # 命令行界面
│   └── app.py            # Flask应用(可选)
├── tests/
│   ├── __init__.py
│   └── test_task.py      # 单元测试
├── README.md             # 项目文档
├── requirements.txt      # 依赖文件
└── setup.py              # 项目安装配置

2. 安装依赖

在项目根目录创建requirements.txt:

requests==2.31.0
flask==2.3.2

运行以下命令安装依赖:

bash

pip install -r requirements.txt

3. 实现任务类(OOP)

在src/task.py中定义任务类,使用OOP设计:

python

from datetime import datetime

class Task:
    def __init__(self, title, description, priority, due_date, status="pending"):
        self.title = title
        self.description = description
        self.priority = priority  # 1(低)到5(高)
        self.due_date = datetime.strptime(due_date, "%Y-%m-%d")
        self.status = status
        self.created_at = datetime.now()

    def mark_complete(self):
        self.status = "completed"

    def to_dict(self):
        return {
            "title": self.title,
            "description": self.description,
            "priority": self.priority,
            "due_date": self.due_date.strftime("%Y-%m-%d"),
            "status": self.status,
            "created_at": self.created_at.strftime("%Y-%m-%d %H:%M:%S")
        }

    def __str__(self):
        return f"{self.title} (Priority: {self.priority}, Due: {self.due_date.strftime('%Y-%m-%d')}, Status: {self.status})"

4. 实现数据库操作

在src/database.py中实现SQLite数据库操作:

python

import sqlite3
from .task import Task

class TaskDatabase:
    def __init__(self, db_name="tasks.db"):
        self.db_name = db_name
        self._init_db()

    def _init_db(self):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS tasks (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT NOT NULL,
                    description TEXT,
                    priority INTEGER,
                    due_date TEXT,
                    status TEXT,
                    created_at TEXT
                )
            """)
            conn.commit()

    def add_task(self, task):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                INSERT INTO tasks (title, description, priority, due_date, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?)
            """, (
                task.title,
                task.description,
                task.priority,
                task.due_date.strftime("%Y-%m-%d"),
                task.status,
                task.created_at.strftime("%Y-%m-%d %H:%M:%S")
            ))
            conn.commit()

    def get_all_tasks(self):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM tasks")
            rows = cursor.fetchall()
            tasks = []
            for row in rows:
                task = Task(
                    title=row[1],
                    description=row[2],
                    priority=row[3],
                    due_date=row[4],
                    status=row[5]
                )
                tasks.append(task)
            return tasks

    def update_task_status(self, task_id, status):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("UPDATE tasks SET status = ? WHERE id = ?", (status, task_id))
            conn.commit()

5. 实现API调用

在src/api.py中调用OpenWeatherMap API获取天气信息:

python

import requests

class WeatherAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "<http://api.openweathermap.org/data/2.5/weather>"

    def get_weather(self, city):
        params = {"q": city, "appid": self.api_key, "units": "metric"}
        response = requests.get(self.base_url, params=params)
        if response.status_code == 200:
            data = response.json()
            return f"Weather in {city}: {data['weather'][0]['description']}, {data['main']['temp']}°C"
        return "Failed to fetch weather data"

注意:你需要从OpenWeatherMap获取免费API密钥,并将其添加到代码中。

6. 实现命令行界面

在src/cli.py中实现简单的CLI:

python

from .task import Task
from .database import TaskDatabase
from .api import WeatherAPI

def main():
    db = TaskDatabase()
    weather_api = WeatherAPI("YOUR_API_KEY")  # 替换为你的API密钥
    while True:
        print("\n1. Add Task\n2. View Tasks\n3. Complete Task\n4. Get Weather\n5. Exit")
        choice = input("Choose an option: ")
        if choice == "1":
            title = input("Title: ")
            description = input("Description: ")
            priority = int(input("Priority (1-5): "))
            due_date = input("Due date (YYYY-MM-DD): ")
            task = Task(title, description, priority, due_date)
            db.add_task(task)
            print("Task added!")
        elif choice == "2":
            tasks = db.get_all_tasks()
            for i, task in enumerate(tasks, 1):
                print(f"{i}. {task}")
        elif choice == "3":
            task_id = int(input("Task ID to complete: "))
            db.update_task_status(task_id, "completed")
            print("Task marked as completed!")
        elif choice == "4":
            city = input("Enter city: ")
            print(weather_api.get_weather(city))
        elif choice == "5":
            break

if __name__ == "__main__":
    main()

Day 29: 测试与完善

1. 编写单元测试

在tests/test_task.py中编写单元测试:

python

import unittest
from src.task import Task
from src.database import TaskDatabase
import os

class TestTaskManager(unittest.TestCase):
    def setUp(self):
        self.db = TaskDatabase("test_tasks.db")
        self.task = Task("Test Task", "Description", 3, "2025-12-31")

    def test_task_creation(self):
        self.assertEqual(self.task.title, "Test Task")
        self.assertEqual(self.task.status, "pending")

    def test_mark_complete(self):
        self.task.mark_complete()
        self.assertEqual(self.task.status, "completed")

    def test_add_task_to_db(self):
        self.db.add_task(self.task)
        tasks = self.db.get_all_tasks()
        self.assertEqual(len(tasks), 1)
        self.assertEqual(tasks[0].title, "Test Task")

    def tearDown(self):
        os.remove("test_tasks.db")

if __name__ == "__main__":
    unittest.main()

运行测试:

bash

python -m unittest tests/test_task.py

2. 添加Flask Web界面(可选)

如果想添加Web界面,在src/app.py中实现Flask应用:

python

from flask import Flask, request, render_template
from database import TaskDatabase
from task import Task

app = Flask(__name__)
db = TaskDatabase()

@app.route("/")
def index():
    tasks = db.get_all_tasks()
    return render_template("index.html", tasks=tasks)

@app.route("/add", methods=["POST"])
def add_task():
    title = request.form["title"]
    description = request.form["description"]
    priority = int(request.form["priority"])
    due_date = request.form["due_date"]
    task = Task(title, description, priority, due_date)
    db.add_task(task)
    return redirect("/")

if __name__ == "__main__":
    app.run(debug=True)

创建templates/index.html:

html

<!DOCTYPE html>
<html>
<head><title>Task Manager</title></head>
<body>
    <h1>Task Manager</h1>
    <form method="post" action="/add">
        <input type="text" name="title" placeholder="Title" required>
        <textarea name="description" placeholder="Description"></textarea>
        <input type="number" name="priority" placeholder="Priority (1-5)" min="1" max="5" required>
        <input type="date" name="due_date" required>
        <button type="submit">Add Task</button>
    </form>
    <h2>Tasks</h2>
    <ul>
        {% for task in tasks %}
        <li>{{ task.title }} (Priority: {{ task.priority }}, Due: {{ task.due_date }})</li>
        {% endfor %}
    </ul>
</body>
</html>

3. 完善代码

  • 添加输入验证(例如,确保优先级在1-5之间,日期格式正确)。
  • 优化CLI界面,添加更多功能(如编辑任务、删除任务)。
  • 处理API调用中的异常情况。

Day 30: 文档与部署

1. 编写README

在项目根目录创建README.md:

markdown

# Task Manager

A Python-based task management application with CLI and optional Web interface.

## Features
- Create, view, update, and delete tasks.
- Store tasks in SQLite database.
- Fetch weather information for task locations using OpenWeatherMap API.
- Command-line interface (CLI) and optional Flask-based Web interface.
- Unit tests with `unittest`.

## Installation
1. Clone the repository:
   ```bash
   git clone <https://github.com/yourusername/todo_manager.git>
   cd todo_manager
  1. Install dependencies:bash
  2. pip install -r requirements.txt
  3. Set up OpenWeatherMap API key:
  4. Get an API key from OpenWeatherMap.
  5. Replace YOUR_API_KEY in src/cli.py or set it as an environment variable.

Usage

CLI

Run the CLI:

bash

python src/cli.py

Follow the menu to add tasks, view tasks, mark tasks as completed, or fetch weather data.

Web Interface (Optional)

Run the Flask app:

bash

python src/app.py

Open http://localhost:5000 in your browser.

Testing

Run unit tests:

bash

python -m unittest tests/test_task.py

Project Structure

todo_manager/
├── src/                # Source code
├── tests/              # Unit tests
├── templates/          # Flask templates
├── README.md           # Documentation
└── requirements.txt    # Dependencies

License

MIT License


#### 2. 部署到GitHub
1. 初始化Git仓库:
   ```bash
   git init
   git add .
   git commit -m "Initial commit"
  1. 创建GitHub仓库并推送:bash
  2. git remote add origin <https://github.com/yourusername/todo_manager.git> git branch -M main git push -u origin main

3. 优化与提交

  • 确保代码通过所有测试。
  • 检查README.md是否清晰,包含所有必要信息。
  • 提交最终代码:bash
  • git add . git commit -m "Complete task manager project" git push

总结

通过这三天的综合项目,你完成了一个功能完整的任务管理器,涵盖了以下Python进阶技能:

  • OOP:使用类(Task、TaskDatabase)组织代码。
  • 数据库:使用SQLite存储和查询任务。
  • API调用:通过OpenWeatherMap API获取天气数据。
  • 测试:编写单元测试确保代码可靠性。
  • 文档:撰写清晰的README。
  • 部署:将项目托管到GitHub。

如果需要进一步扩展(例如添加用户认证、REST API或更复杂的Web界面),可以告诉我,我会提供更多指导!祝贺你完成Python进阶课程!

相关推荐

用Python编制生成4位数字字母混合验证码

我们登录一些网站、APP的时候经常会有验证码,这个为了防止有人不停的去试探密码,还有发送短信验证之前,输入验证码就可以减少误点,错误操作等等。可以提高安全性,我们可以生成数字,也可以生成字母,也可...

Python电子发票管理工具4:前后端业务逻辑实现

用一系列文章介绍如何用python写一个发票管理小工具。在前面的文章中前端页面和后端框架已经实现,本文将介绍功能实现的代码。数据库操作使用sqlalchemy操作sqlite数据库。sqlalchem...

【代码抠图】4行Python代码帮你消除图片背景

在修图工具满天飞的年代其实仍然还有很多人不会扣图(比如我),在很多需要去除某些照片上面的背景的时候就会很难受,所以今天就给不会扣图的小伙伴们来带一个简单的代码扣图教程,只需要4行代码,不用再多了。准备...

Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!

Python3.14重磅更新!UUIDv6/v7/v8强势来袭,别再用uuid4()啦!为什么说UUID升级是2025年Python开发者的必学技能?在当今互联网应用中,UU...

殊途同归 python 第 4 节:有趣的键值对(字典)

字典数据的突出特点就是“键”和“值”,前文已经简单介绍过,本文来聊聊关于字典的几个高级玩法。1.函数打包后,通过键来调用globalf1,f2a={"k1":f1,"k2...

更有效地使用 Python Pandas 的 4 个技巧

一个简单而实用的指南照片由simonsun在Unsplash上拍摄Pandas是一个用于数据分析和操作任务的非常实用且功能强大的库。自2019年以来,我一直在使用Pandas,它始终能够为我...

4.python学习笔记-集合(python里面集合)

1.关于集合集合是一类元素无序不重复的数据结构,常用场景是元素去重和集合运算。python可以使用大括号{}或者set()函数创建集合,如果创建一个空集合必须用set()而不是{},因为{}是用来表示...

python生成4种UUID(python随机生成uuid)

总结了一份python生成4种UUID的代码:UUID用4种uuid生成方法:uuid1:基于时间戳由MAC地址、当前时间戳、随机数字。保证全球范围内的唯一性。但是由于MAC地址使用会带来安全问题...

你不知道的4种方法:python方法绘制扇形

1说明:=====1.1是问答中的我的一个回答。1.1因为问答中没有代码块的,所以我改为这里写文章,然后链接过去。1.24种方法:turtle法、OpenCV法、pygame法和matplot...

30天学会Python编程:4. Python运算符与表达式

4.1运算符概述4.1.1运算符分类Python运算符可分为以下几大类:4.1.2运算符优先级表4-1Python运算符优先级(从高到低)运算符描述示例**指数2**3→8~+-按位取...

这3个高级Python函数,不能再被你忽略了

全文共1657字,预计学习时长3分钟Python其实也可以带来很多乐趣。重新审视一些一开始并不被人们熟知的内置函数并没有想象中那么难,但为什么要这么做呢?今天,本文就来仔细分析3个在日常工作中或多或少...

beautifulSoup4,一个超实用的python库

一.前言我们在学习python爬虫的时候,数据提取是一个常见的任务。我们一般使用正则表达式,lxml等提取我们需要的数据,今天我们介绍一个新的库beautifulSoup4,使用它您可以从HTML和...

AI指导:打造第一个Python应用(4)(python ai开发)

眼瞅着迈过几个里程碑,与目标越来越近。尽管过程中照旧因返工而心焦,而欣喜与急躁比例,是喜悦运大于焦虑。从初次熟悉智能大模型,尝试编程起步,不定期进行复盘反思,这是小助手指导编程的第四篇。复盘以为记。需...

wxPython 4.2.0终于发布了(wxpython安装教程)

  wxPython是Python语言的跨平台GUI工具包。使用wxPython,软件开发人员可以为他们的Python应用程序创建真正的本地用户界面,这些应用程序在Windows、Ma...

《Python学习手册(第4版)》PDF开放下载,建议收藏

书籍简介如果你想动手编写高效、高质量并且很容易与其他语言和工具集成的代码,本书将快速地帮助你利用Python提高效率。本书基于Python专家的流程培训课程编写,内容通俗易懂。本书包含很多注释的例子和...

取消回复欢迎 发表评论: