Skip to content

Commit c9ec408

Browse files
committed
update:adjust file structure
1 parent 9ecd2c2 commit c9ec408

File tree

3 files changed

+47
-47
lines changed

3 files changed

+47
-47
lines changed

main.py

Lines changed: 7 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
import datetime
22
import uuid
3-
import random
43
import asyncio
54
from pathlib import Path
65

76
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
87
from starlette.responses import HTMLResponse, FileResponse
98
from starlette.staticfiles import StaticFiles
109

11-
from sqlalchemy import or_, select, update, delete
10+
from sqlalchemy import select, update
1211
from sqlalchemy.ext.asyncio.session import AsyncSession
1312

1413
import settings
15-
from database import get_session, Codes, init_models, engine
16-
from storage import STORAGE_ENGINE
14+
from utils import delete_expire_files, storage, get_code
15+
from database import get_session, Codes, init_models
1716
from depends import admin_required, IPRateLimit
1817

1918
app = FastAPI(debug=settings.DEBUG)
@@ -25,8 +24,6 @@
2524
STATIC_URL = settings.STATIC_URL
2625
app.mount(STATIC_URL, StaticFiles(directory=DATA_ROOT), name="static")
2726

28-
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
29-
3027

3128
@app.on_event('startup')
3229
async def startup():
@@ -46,31 +43,6 @@ async def startup():
4643
ip_limit = IPRateLimit()
4744

4845

49-
async def delete_expire_files():
50-
while True:
51-
async with AsyncSession(engine, expire_on_commit=False) as s:
52-
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
53-
exps = (await s.execute(query)).scalars().all()
54-
files = []
55-
exps_ids = []
56-
for exp in exps:
57-
if exp.type != "text":
58-
files.append(exp.text)
59-
exps_ids.append(exp.id)
60-
await storage.delete_files(files)
61-
query = delete(Codes).where(Codes.id.in_(exps_ids))
62-
await s.execute(query)
63-
await s.commit()
64-
await asyncio.sleep(random.randint(60, 300))
65-
66-
67-
async def get_code(s: AsyncSession):
68-
code = random.randint(10000, 99999)
69-
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
70-
code = random.randint(10000, 99999)
71-
return str(code)
72-
73-
7446
@app.get(f'/{settings.ADMIN_ADDRESS}')
7547
async def admin():
7648
return HTMLResponse(admin_html)
@@ -138,7 +110,8 @@ async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depend
138110

139111
@app.post('/share')
140112
async def share(background_tasks: BackgroundTasks, text: str = Form(default=None), style: str = Form(default='2'),
141-
value: int = Form(default=1), file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
113+
value: int = Form(default=1), file: UploadFile = File(default=None),
114+
s: AsyncSession = Depends(get_session)):
142115
code = await get_code(s)
143116
if style == '2':
144117
if value > 7:
@@ -162,20 +135,11 @@ async def share(background_tasks: BackgroundTasks, text: str = Form(default=None
162135
background_tasks.add_task(storage.save_file, file, _text)
163136
else:
164137
size, _text, _type, name = len(text), text, 'text', '文本分享'
165-
info = Codes(
166-
code=code,
167-
text=_text,
168-
size=size,
169-
type=_type,
170-
name=name,
171-
count=exp_count,
172-
exp_time=exp_time,
173-
key=key
174-
)
138+
info = Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key)
175139
s.add(info)
176140
await s.commit()
177141
return {
178-
'detail': '分享成功,请点击文件箱查看取件码',
142+
'detail': '分享成功,请点击取件码按钮查看上传列表',
179143
'data': {'code': code, 'key': key, 'name': name, 'text': _text}
180144
}
181145

storage.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,19 @@ async def get_text(self, file: UploadFile, key: str):
2323
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
2424
if not path.exists():
2525
path.mkdir(parents=True)
26-
filepath = path / f'{key}.{ext}'
27-
text = f"{self.STATIC_URL}/{filepath.relative_to(self.DATA_ROOT)}"
26+
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT).relative_to(self.DATA_ROOT)}"
2827
return text
2928

30-
async def get_size(self, file: UploadFile):
29+
@staticmethod
30+
async def get_size(file: UploadFile):
3131
f = file.file
3232
f.seek(0, os.SEEK_END)
3333
size = f.tell()
3434
f.seek(0, os.SEEK_SET)
3535
return size
3636

37-
def _save(self, filepath, file: BinaryIO):
37+
@staticmethod
38+
def _save(filepath, file: BinaryIO):
3839
with open(filepath, 'wb') as f:
3940
chunk_size = 256 * 1024
4041
chunk = file.read(chunk_size)

utils.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import datetime
2+
import random
3+
import asyncio
4+
from sqlalchemy import or_, select, delete
5+
from sqlalchemy.ext.asyncio.session import AsyncSession
6+
import settings
7+
from database import Codes, engine
8+
from storage import STORAGE_ENGINE
9+
10+
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
11+
12+
13+
async def delete_expire_files():
14+
while True:
15+
async with AsyncSession(engine, expire_on_commit=False) as s:
16+
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
17+
exps = (await s.execute(query)).scalars().all()
18+
files = []
19+
exps_ids = []
20+
for exp in exps:
21+
if exp.type != "text":
22+
files.append(exp.text)
23+
exps_ids.append(exp.id)
24+
await storage.delete_files(files)
25+
query = delete(Codes).where(Codes.id.in_(exps_ids))
26+
await s.execute(query)
27+
await s.commit()
28+
await asyncio.sleep(random.randint(60, 300))
29+
30+
31+
async def get_code(s: AsyncSession):
32+
code = random.randint(10000, 99999)
33+
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
34+
code = random.randint(10000, 99999)
35+
return str(code)

0 commit comments

Comments
 (0)