Flutter + FastAPI 30天速成计划自用并实践-第7天

Day 7 详细学习计划:内容导入脚本开发

学习目标

  • 创建批量内容导入脚本
  • 学习自动化内容管理
  • 完善后端功能

好,在day6的基础上添加一个脚本,然后运行这个脚本就能将学习记录导入到数据库中了

创建一个advanced_import.py脚本,这个脚本可以将markdown文件,导入到数据库中,在fastapi接口中可以用get方法查看到

python 复制代码
import argparse
from datetime import datetime
from sqlmodel import Session
from database import engine, create_db_and_tables
from models.article import Article

def import_articles(file_path: str, clear_existing: bool = False):
    """导入文章的通用函数"""
    # 创建数据库表
    create_db_and_tables()
    
    # 读取Markdown文件
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 解析Markdown文件获取标题
    lines = content.split('\n')
    title = "默认标题"
    for line in lines:
        if line.startswith('# '):
            title = line[2:]  # 移除 "# " 前缀
            break
    
    # 使用文件名(不含扩展名)作为备选标题
    if title == "默认标题":
        import os
        title = os.path.splitext(os.path.basename(file_path))[0]
    
    # 导入文章
    with Session(engine) as session:
        # 如果需要清除现有数据
        if clear_existing:
            # 删除所有现有文章
            articles = session.query(Article).all()
            for article in articles:
                session.delete(article)
            session.commit()
            print("已清除现有文章")
        
        # 创建新文章对象
        article = Article(
            title=title,
            content=content,
            created_at=datetime.now()
        )
        
        # 添加到数据库
        session.add(article)
        session.commit()
        session.refresh(article)
        print(f"成功导入文章: {article.title}")

def main():
    parser = argparse.ArgumentParser(description='导入文章到数据库')
    parser.add_argument('file', help='要导入的Markdown文件路径')
    parser.add_argument('--clear', action='store_true', help='导入前清除现有数据')
    
    args = parser.parse_args()
    
    import_articles(args.file, args.clear)

if __name__ == "__main__":
    # 为了测试方便,可以暂时使用固定路径
    import_articles('./第七天的内容.md', True)
    # main()  # 正常情况下使用命令行参数

上面我测试了下将第七天的内容md文件导入到数据库中

使用get请求访问接口,就可以看到导入的md文件内容了
http://127.0.0.1:8000/api/v1/articles/

在浏览器中直接输入网址也可以,默认浏览器是识别的get方法,所以可以访问

结果就是
[{"title":"Day 7 详细学习计划:内容导入脚本开发","content":"# Day 7 详细学习计划:内容导入脚本开发......

到今天后端就先这样了,明天开始学习flutter,

相关推荐
九狼4 小时前
Flutter URL Scheme 跨平台跳转
人工智能·flutter·github
_squirrel6 小时前
记录一次 Flutter 升级遇到的问题
flutter
Haha_bj7 小时前
Flutter——状态管理 Provider 详解
flutter·app
曲幽7 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
MakeZero10 小时前
Flutter那些事-展示型组件篇
flutter
赤心Online10 小时前
从零开始掌握 Shorebird:Flutter 热更新实战指南
flutter
wangruofeng11 小时前
AI 助力 Flutter 3.27 升级到 3.38 完整指南:两周踩坑与实战复盘
flutter·ios·ai编程
Zsnoin能1 天前
Flutter仿ios液态玻璃效果
flutter
闲云一鹤1 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽1 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi