侧边栏壁纸
博主头像
KALI零一个人学习编程博主等级

行动起来,活在当下

  • 累计撰写 3 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

未命名文章

Administrator
2024-02-14 / 0 评论 / 0 点赞 / 19 阅读 / 6274 字
温馨提示:
本文最后更新于 2024-02-14,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

代码

from fastapi import APIRouter, Form, HTTPException, Request,status,Depends
from typing import Optional, List
from pydantic import BaseModel
import httpx
import logging
import json
from datetime import datetime,timedelta
from enum import Enum
from lunarcalendar.festival import festivals


router = APIRouter()


# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("fastapi")



# 自定义HTTP状态码枚举类
class CustomHTTPStatusCodes(str, Enum):
    OK = "200"
    BAD_REQUEST = "400"
    INTERNAL_SERVER_ERROR = "500"

class CountdownResponse(BaseModel):
    festivals_info: List[str]
    status_code: CustomHTTPStatusCodes
    message: Optional[str] = 'Initialization'

# 获取当前时间(精确到秒)
current_datetime = datetime.now()

# 定义当前年份和下一年份
current_year = current_datetime.year
next_year = current_year + 1

# 定义需要计算倒计时或显示祝福的节日名称列表及对应的祝福语
chinese_festivals_info = [
    ("除夕", "除夕快乐!"),
    ("春节", "春节快乐,恭喜发财!"),
    ("中秋节", "中秋佳节,祝你阖家团圆,幸福美满!"),
    ("情人节", "情人节快乐,愿我们的爱情永远甜蜜!"),
    ("元旦", "元旦快乐,万事如意!"),
    ("国庆节", "国庆节快乐,祝愿祖国繁荣昌盛!"),
    ("妇女节", "妇女节快乐,女性朋友们永远年轻美丽!"),
    ("植树节", "植树节快乐,为地球绿化,共建美好家园!"),
    ("清明节", "清明节快乐,缅怀先人,珍爱生命!"),
    ("劳动节", "劳动节快乐,辛勤劳动创造幸福生活!"),
    ("青年节", "青年节快乐,年轻就是无限可能!"),
    ("护士节", "护士节快乐,感谢你们默默守护生命!"),
    ("母亲节", "母亲节快乐,妈妈您是世界上最美好的存在!"),
    ("儿童节", "儿童节快乐,愿所有的孩子们都健康快乐成长!"),
    ("父亲节", "父亲节快乐,爸爸您是我心中最伟大的人!"),
    ("教师节", "教师节快乐,感谢您为我们的教育付出!"),
    ("万圣夜", "万圣夜快乐,欢乐不给鬼留!"),
    ("感恩节", "感恩节快乐,感恩有您,生活更美好!"),
    ("平安夜", "平安夜快乐,愿平安与你同在,幸福永远!"),
    ("圣诞节", "圣诞节快乐,愿节日的喜悦与你同在!"),
    ("复活节", "复活节快乐,愿主的爱与你同在,重生喜悦!"),
    ("腊八节", "腊八节快乐,祈愿福寿安康,吉祥如意!"),
    ("小年", "小年快乐,年年有余,岁岁平安!"),
    ("破五节", "破五节快乐,欢庆美好时光!"),
    ("元宵节", "元宵节快乐,灯火辉煌,团团圆圆!"),
    ("龙抬头", "龙抬头快乐,吉祥如意,龙飞凤舞!"),
    ("端午节", "端午节快乐,粽香满屋,欢乐团圆!"),
    ("中元节", "中元节快乐,祭奠先祖,永怀思念!"),
    ("重阳节", "重阳节快乐,祝愿长寿安康,幸福美满!"),
    ("寒衣节", "寒衣节快乐,冬至将至,寒衣暖心!"),
    ("冬节", "冬节快乐,欢乐满堂,团圆幸福!"),
]


#节日倒计时接口
@router.get("/countdown", response_model=CountdownResponse)
async def countdown(festival_name: Optional[str] = None, limit: Optional[int] = 6):
    try:
        current_datetime = datetime.now()  # 获取当前时间(精确到秒)
        found_fest_info_list = []  # 保存找到的节日信息列表

        chinese_festivals = chinese_festivals_info if not festival_name else [(fest, greeting) for fest, greeting in chinese_festivals_info if fest == festival_name]
        if not chinese_festivals:
            return CountdownResponse(
                festivals_info=[f"未找到节日'{festival_name}'的信息"],
                status_code=CustomHTTPStatusCodes.BAD_REQUEST,
                message=f"未找到节日'{festival_name}'的信息"
            )

        # 阳历节日计算
        for fest_info in chinese_festivals:  # 遍历节日信息列表
            festival_name, festival_greeting = fest_info  # 解包节日信息
            for year_offset in [0, 1]:  # 首先尝试当前年份,然后尝试下一年
                fest_date = None
                for fest in festivals:
                    if fest.get_lang('zh') == festival_name:
                        try:
                            fest_date = datetime.combine(fest(current_year + year_offset), datetime.min.time())
                            break
                        except (AttributeError, ValueError):
                            continue

                if fest_date is not None and (fest_date.date() >= current_datetime.date()):  # 找到了符合条件的未来日期或当天
                    countdown = (fest_date - current_datetime).total_seconds()
                    if countdown > 0:  # 如果是未来日期,则计算倒计时
                        days, remainder = divmod(countdown, 86400)
                        hours, remainder = divmod(remainder, 3600)
                        minutes, seconds = divmod(remainder, 60)
	                        festival_info1 = f"{festival_name}({current_year + year_offset}年):{fest_date},倒计时: {int(days)}天{int(hours)}小时{int(minutes)}分钟{int(seconds)}秒"
                        festival_info = f"{festival_name}({current_year + year_offset}年): {int(days)}天{int(hours)}小时{int(minutes)}分钟{int(seconds)}秒"
                        found_fest_info_list.append((fest_date, festival_info))  # 添加节日信息到列表中,注意这里是一个元组,包含 fest_date 和 festival_info
                        break
                    else:  # 当天为节日
	                        festival_info1 = f"{festival_name}({current_year + year_offset}年):{fest_date},祝福语:{festival_greeting}"
	                        festival_info = f"{festival_name}({current_year + year_offset}年):{festival_greeting}"
                        found_fest_info_list.append((fest_date, festival_info))  # 添加节日信息到列表中,注意这里是一个元组,包含 fest_date 和 festival_info
                        break

        if found_fest_info_list:  # 如果找到了节日信息,对列表进行倒序排序,并返回对应的响应
            sorted_fest_info_list = sorted(found_fest_info_list, key=lambda x: x[0])  # 根据 fest_date 正序排序
            sorted_fest_info_list = [info[1] for info in sorted_fest_info_list[:limit]]  # 只取节日信息部分,去除 fest_date,并且根据传入的 limit 参数切片
            return CountdownResponse(
                festivals_info=sorted_fest_info_list,
                status_code=CustomHTTPStatusCodes.OK,
                message="Success"
            )
        else:  # 如果没有找到节日信息,返回默认的响应
            print("未能找到任何节日在未来两年内的日期")
            return CountdownResponse(
                festivals_info=["未能找到任何节日在未来两年内的日期"],
                status_code=CustomHTTPStatusCodes.OK,
                message="Success"
            )

    except HTTPException as e:
        # 如果捕获到HTTP异常,返回错误信息及相应的状态码
        return CountdownResponse(
            festivals_info=["获取异常:"+str(e.detail)],
            status_code=CustomHTTPStatusCodes.BAD_REQUEST,
            message=str(e.detail)
        )
    except Exception as ex:
        # 其他未知异常,返回服务器内部错误及状态码
        return CountdownResponse(
            festivals_info=["获取异常:"+str(ex)],
            status_code=CustomHTTPStatusCodes.INTERNAL_SERVER_ERROR,
            message=str(ex)
        )

0

评论区