Upload 2 files
Browse files- main.py +54 -0
- requirements.txt +0 -0
main.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
from generate_image import generate_image
|
| 8 |
+
from fastapi.staticfiles import StaticFiles
|
| 9 |
+
|
| 10 |
+
app = FastAPI()
|
| 11 |
+
# 挂载 tmp 文件夹下的静态文件
|
| 12 |
+
app.mount("/static", StaticFiles(directory="/tmp"), name="static")
|
| 13 |
+
# 添加跨域支持
|
| 14 |
+
origins = [
|
| 15 |
+
"*"
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
app.add_middleware(
|
| 19 |
+
CORSMiddleware,
|
| 20 |
+
allow_origins=origins,
|
| 21 |
+
allow_credentials=True,
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# 创建一个模型,用于接收 markdown 字符串
|
| 27 |
+
class Markdown(BaseModel):
|
| 28 |
+
markdown: str
|
| 29 |
+
|
| 30 |
+
# 创建一个路由,用于接收 markdown 字符串并生成图片
|
| 31 |
+
@app.post("/generate_image")
|
| 32 |
+
async def generate_image_endpoint(markdown: Markdown):
|
| 33 |
+
# 生成随机文件名
|
| 34 |
+
image_filename = '/tmp/'+str(uuid.uuid4()) + ".png"
|
| 35 |
+
# 调用 generate_image 函数来生成图片
|
| 36 |
+
generate_image(markdown.markdown, image_filename)
|
| 37 |
+
# 返回图片的路径
|
| 38 |
+
return {"image_path": f"{image_filename}"}
|
| 39 |
+
|
| 40 |
+
# 创建一个函数,用于清理过期的图片
|
| 41 |
+
def clean_expired_images():
|
| 42 |
+
expiration_time = int(os.environ.get("EXPIRATION_TIME", "3600")) # 默认过期时间为1小时
|
| 43 |
+
current_time = time.time()
|
| 44 |
+
for filename in os.listdir("/tmp"):
|
| 45 |
+
file_path = os.path.join("/tmp", filename)
|
| 46 |
+
if current_time - os.path.getmtime(file_path) > expiration_time:
|
| 47 |
+
os.remove(file_path)
|
| 48 |
+
|
| 49 |
+
# 创建一个路由,用于触发清理过期的图片
|
| 50 |
+
@app.delete("/clean_images")
|
| 51 |
+
async def clean_images_endpoint():
|
| 52 |
+
# 调用 clean_expired_images 函数来清理过期的图片
|
| 53 |
+
clean_expired_images()
|
| 54 |
+
return {"message": "Images cleaned"}
|
requirements.txt
ADDED
|
Binary file (486 Bytes). View file
|
|
|