fastapi_event.py
1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from contextlib import asynccontextmanager
from tortoise import Tortoise
from app.job.job import scheduler
from fastapi import FastAPI
from app.config.tortoise_config import getTortoiseConfig
import logging
logger = logging.getLogger(__name__)
async def init():
# 初始化链接
logger.info("开始初始化数据库")
await Tortoise.init(config=getTortoiseConfig().model_dump())
# 生成数据库表数据
logger.info("开始生成数据库表")
await Tortoise.generate_schemas()
async def close():
await Tortoise.close_connections()
# 使用asynccontextmanager装饰器定义一个异步上下文管理器函数lifespan
@asynccontextmanager
async def lifespan(app: FastAPI):
# 开始apscheduler
scheduler.start()
logging.info("apscheduler启动完成")
await init()
logging.info("初始化数据库完成")
# 获取程序开始执行的时间
start_time = time.time()
param = SpiderParams(
startDate="2024-12-20",
endDate="2024-12-21",
target_type=[
TypeEnum.ANIME,
TypeEnum.EPISODES,
TypeEnum.MOVIE,
TypeEnum.VARIETY,
],
url="http://guduodata.com",
)
print(param.get_time_range())
asyncio.run(scrawl_and_save(param))
print(f"程序执行耗时时间:{(time.time() - start_time) / 1000}")
yield
# 在异步上下文管理器中,"退出上下文"时清理机器学习模型,释放资源
scheduler.shutdown()
logging.info("apscheduler关闭完成")
await close()
logging.info("关闭数据库完成")