# fastapi-project **Repository Path**: LIU_LOWELL/fastapi-project ## Basic Information - **Project Name**: fastapi-project - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-12-06 - **Last Updated**: 2024-12-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 数据库操作 1. 初始化数据库 ``` aerich init -t app01.config.database.DATABASE_CONFIG ``` 2. 模型变更生成迁移脚本 ``` aerich migrate --name "fix_syntax_error" ``` 3. 更新数据库 ``` aerich upgrade ``` 4. sqlite 和 mysql 等数据库有不兼容内容,下面是 sqlite 支持的字段类型 | Tortoise 字段类型 | Tortoise 字段类型 | | :------------------- | :---------------------: | | fields.IntField | 支持 | | fields.CharField | 支持 | | fields.TextField | 支持 | | fields.DatetimeField | 支持 | | fields.JSONField | 部分支持(Python 3.9+) | | fields.BooleanField | 支持 | | fields.FloatField | 支持 | 5. 回滚到某个版本 ``` aerich downgrade -n ``` # 定时任务 1. 基于 interval 方式实现不同时间间隔的定时任务 - 秒级定时任务 ``` scheduler.add_job(clean_expired_data, "interval", seconds=1) ``` - 分钟级定时任务 ``` scheduler.add_job(clean_expired_data, "interval", minutes=1) ``` - 小时级定时任务 ``` scheduler.add_job(clean_expired_data, "interval", hours=1) ``` - 天级定时任务(使用 interval 方式) ``` scheduler.add_job(clean_expired_data, "interval", days=1) ``` 2. 基于 cron 方式实现更灵活的定时任务(适用于月、季度、年等复杂时间规则) - cron 表达式基础 cron 表达式是一个字符串,用于定义任务执行的时间规则。它由 5 个(或 6 个)字段组成,从左到右分别表示分钟、小时、日、月、周(可选的年份)。每个字段可以使用具体的值、范围、通配符等来定义时间。例如,_表示所有可能的值,_/2 表示每隔 2 个单位(如\*/2 在分钟字段表示每隔 2 分钟)。 - 月级定时任务 在这里,month = '1-12'表示每个月都执行,day = '1'指定在每月的 1 号执行 monthly_report 函数。 ``` scheduler.add_job(monthly_report, 'cron', month = '1-12', day = '1') ``` - 季度级定时任务(一种实现方式) 通过 month = '1,4,7,10'指定了季度的起始月份(1 月、4 月、7 月、10 月),day = '1'表示在这些月份的 1 号执行 quarterly_audit 函数,从而实现每个季度执行一次任务的目的。 ``` scheduler.add_job(quarterly_audit, 'cron', month = '1,4,7,10', day = '1') ``` - 年度定时任务 对于 annual_summary 函数,month = '1'和 day = '1'使得任务在每年的 1 月 1 日执行。 ``` scheduler.add_job(annual_summary, 'cron', month = '1', day = '1') ``` # Celery 启动celery异步任务 ``` ccelery -A app01.config.celery.celery_app worker -l info --queues=default ``` celery查看任务列表,使用flower工具 ```commandline celery -A app01.config.celery.celery_app --broker=redis://127.0.0.1:6379/1 flower ``` 访问如下地址可以查看 ```commandline http://127.0.0.1:5555/ ```