Skip to content

Commit 2ef6c75

Browse files
committed
增加定时清理过期文件
1 parent bec3eb2 commit 2ef6c75

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

main.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import uuid
44
import threading
55
import random
6+
import asyncio
7+
68
from fastapi import FastAPI, Depends, UploadFile, Form, File
79
from starlette.requests import Request
810
from starlette.responses import HTMLResponse, FileResponse
@@ -11,7 +13,7 @@
1113
from sqlalchemy import or_, select, update, delete
1214
from sqlalchemy.ext.asyncio.session import AsyncSession
1315

14-
from database import get_session, Codes, init_models
16+
from database import get_session, Codes, init_models, engine
1517

1618
app = FastAPI()
1719
if not os.path.exists('./static'):
@@ -23,6 +25,8 @@
2325
async def startup():
2426
await init_models()
2527

28+
asyncio.create_task(delete_expire_files())
29+
2630

2731
############################################
2832
# 需要修改的参数
@@ -62,6 +66,21 @@ def delete_file(files):
6266
os.remove('.' + file['text'])
6367

6468

69+
async def delete_expire_files():
70+
while True:
71+
async with AsyncSession(engine, expire_on_commit=False) as s:
72+
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
73+
exps = (await s.execute(query)).scalars().all()
74+
await asyncio.to_thread(delete_file, [{'type': old.type, 'text': old.text} for old in exps])
75+
76+
exps_ids = [exp.id for exp in exps]
77+
query = delete(Codes).where(Codes.id.in_(exps_ids))
78+
await s.execute(query)
79+
await s.commit()
80+
81+
await asyncio.sleep(random.randint(60, 300))
82+
83+
6584
async def get_code(s: AsyncSession):
6685
code = random.randint(10000, 99999)
6786
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
@@ -104,7 +123,7 @@ async def admin_delete(request: Request, code: str, s: AsyncSession = Depends(ge
104123
if request.headers.get('pwd') == admin_password:
105124
query = select(Codes).where(Codes.code == code)
106125
file = (await s.execute(query)).scalars().first()
107-
threading.Thread(target=delete_file, args=([{'type': file.type, 'text': file.text}],)).start()
126+
await asyncio.to_thread(delete_file, [{'type': file.type, 'text': file.text}])
108127
await s.delete(file)
109128
await s.commit()
110129
return {'code': 200, 'msg': '删除成功'}
@@ -179,15 +198,6 @@ async def index(request: Request, code: str, s: AsyncSession = Depends(get_sessi
179198
@app.post('/share')
180199
async def share(text: str = Form(default=None), style: str = Form(default='2'), value: int = Form(default=1),
181200
file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
182-
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
183-
exps = (await s.execute(query)).scalars().all()
184-
threading.Thread(target=delete_file, args=([[{'type': old.type, 'text': old.text}] for old in exps],)).start()
185-
186-
exps_ids = [exp.id for exp in exps]
187-
query = delete(Codes).where(Codes.id.in_(exps_ids))
188-
await s.execute(query)
189-
await s.commit()
190-
191201
code = await get_code(s)
192202
if style == '2':
193203
if value > 7:

0 commit comments

Comments
 (0)