|
| 1 | +import datetime |
| 2 | +import os |
| 3 | +import uuid |
| 4 | + |
| 5 | +from fastapi import FastAPI, Depends, UploadFile, Form, File |
| 6 | +from sqlalchemy.orm import Session |
| 7 | +from starlette.requests import Request |
| 8 | +from starlette.responses import HTMLResponse |
| 9 | +import random |
| 10 | + |
| 11 | +from starlette.staticfiles import StaticFiles |
| 12 | + |
| 13 | +import database |
| 14 | +from database import engine, SessionLocal, Base |
| 15 | + |
| 16 | +Base.metadata.create_all(bind=engine) |
| 17 | +app = FastAPI() |
| 18 | +if not os.path.exists('./static'): |
| 19 | + os.makedirs('./static') |
| 20 | +app.mount("/static", StaticFiles(directory="static"), name="static") |
| 21 | +# 过期时间 |
| 22 | +exp_hour = 24 |
| 23 | +# 允许错误次数 |
| 24 | +error_count = 5 |
| 25 | +# 禁止分钟数 |
| 26 | +error_minute = 60 |
| 27 | + |
| 28 | +error_ip_count = {} |
| 29 | + |
| 30 | + |
| 31 | +def get_db(): |
| 32 | + db = SessionLocal() |
| 33 | + try: |
| 34 | + yield db |
| 35 | + finally: |
| 36 | + db.close() |
| 37 | + |
| 38 | + |
| 39 | +def get_code(db: Session = Depends(get_db)): |
| 40 | + code = random.randint(10000, 99999) |
| 41 | + while db.query(database.Codes).filter(database.Codes.code == code).first(): |
| 42 | + code = random.randint(10000, 99999) |
| 43 | + return str(code) |
| 44 | + |
| 45 | + |
| 46 | +def get_file_name(key, ext, file): |
| 47 | + now = datetime.datetime.now() |
| 48 | + path = f'./static/upload/{now.year}/{now.month}/{now.day}/' |
| 49 | + name = f'{key}.{ext}' |
| 50 | + if not os.path.exists(path): |
| 51 | + os.makedirs(path) |
| 52 | + file = file.file.read() |
| 53 | + with open(f'{os.path.join(path, name)}', 'wb') as f: |
| 54 | + f.write(file) |
| 55 | + return key, len(file), path[1:] + name |
| 56 | + |
| 57 | + |
| 58 | +@app.get('/') |
| 59 | +async def index(): |
| 60 | + with open('templates/index.html', 'r') as f: |
| 61 | + return HTMLResponse(f.read()) |
| 62 | + |
| 63 | + |
| 64 | +@app.post('/') |
| 65 | +async def index(request: Request, code: str, db: Session = Depends(get_db)): |
| 66 | + info = db.query(database.Codes).filter(database.Codes.code == code).first() |
| 67 | + error = error_ip_count.get(request.client.host, {'count': 0, 'time': datetime.datetime.now()}) |
| 68 | + if error['count'] > error_count: |
| 69 | + if datetime.datetime.now() - error['time'] < datetime.timedelta(minutes=error_minute): |
| 70 | + return {'code': 404, 'msg': '请求过于频繁,请稍后再试'} |
| 71 | + else: |
| 72 | + error['count'] = 0 |
| 73 | + else: |
| 74 | + if not info: |
| 75 | + error['count'] += 1 |
| 76 | + error_ip_count[request.client.host] = error |
| 77 | + return {'code': 404, 'msg': f'取件码错误,错误5次将被禁止10分钟'} |
| 78 | + else: |
| 79 | + return {'code': 200, 'msg': '取件成功,请点击库查看', 'data': info} |
| 80 | + |
| 81 | + |
| 82 | +@app.get('/share') |
| 83 | +async def share(): |
| 84 | + with open('templates/upload.html', 'r') as f: |
| 85 | + return HTMLResponse(f.read()) |
| 86 | + |
| 87 | + |
| 88 | +@app.post('/share') |
| 89 | +async def share(text: str = Form(default=None), file: UploadFile = File(default=None), db: Session = Depends(get_db)): |
| 90 | + cutoff_time = datetime.datetime.now() - datetime.timedelta(hours=exp_hour) |
| 91 | + db.query(database.Codes).filter(database.Codes.use_time < cutoff_time).delete() |
| 92 | + db.commit() |
| 93 | + code = get_code(db) |
| 94 | + if text: |
| 95 | + info = database.Codes( |
| 96 | + code=code, |
| 97 | + text=text, |
| 98 | + type='text/plain', |
| 99 | + key=uuid.uuid4().hex, |
| 100 | + size=len(text), |
| 101 | + used=True, |
| 102 | + name='分享文本' |
| 103 | + ) |
| 104 | + db.add(info) |
| 105 | + db.commit() |
| 106 | + return {'code': 200, 'msg': '上传成功,请点击文件库查看', |
| 107 | + 'data': {'code': code, 'name': '分享文本', 'text': text}} |
| 108 | + elif file: |
| 109 | + key, size, full_path = get_file_name(uuid.uuid4().hex, file.filename.split('.')[-1], file) |
| 110 | + info = database.Codes( |
| 111 | + code=code, |
| 112 | + text=full_path, |
| 113 | + type=file.content_type, |
| 114 | + key=key, |
| 115 | + size=size, |
| 116 | + used=True, |
| 117 | + name=file.filename |
| 118 | + ) |
| 119 | + db.add(info) |
| 120 | + db.commit() |
| 121 | + return {'code': 200, 'msg': '上传成功,请点击文件库查看', |
| 122 | + 'data': {'code': code, 'name': file.filename, 'text': full_path}} |
| 123 | + else: |
| 124 | + return {'code': 422, 'msg': '参数错误', 'data': []} |
0 commit comments