fixed
This commit is contained in:
@ -1,4 +1,3 @@
|
||||
from copy import deepcopy
|
||||
import mimetypes
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
@ -6,7 +5,7 @@ from time import strftime, time
|
||||
from uuid import uuid1
|
||||
|
||||
import requests
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
from PIL import Image
|
||||
from sqlalchemy.orm import Session
|
||||
|
@ -1,107 +0,0 @@
|
||||
import mimetypes
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from time import time
|
||||
from uuid import uuid1
|
||||
|
||||
import requests
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
from PIL import Image
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import schemas
|
||||
from ..dependencies import get_db
|
||||
from ..sql import crud
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/images", response_model=list[schemas.image.Image], tags=['图片'])
|
||||
def read_pics(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
pics = crud.get_pics(db, skip=skip, limit=limit)
|
||||
return pics
|
||||
|
||||
|
||||
@router.get("/image/detail/{pic_id}", response_model=schemas.image.Image, tags=['图片'])
|
||||
def read_pic_by_id(pic_id: int, db: Session = Depends(get_db)):
|
||||
db_pic = crud.get_pic(db, pic_id=pic_id)
|
||||
if db_pic is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return db_pic
|
||||
|
||||
|
||||
@router.get("/image/{file_path}", tags=['图片'])
|
||||
def get_image(file_path: str, db: Session = Depends(get_db)):
|
||||
image_path = Path(Path.home()).joinpath(
|
||||
'Pictures').joinpath('upload_images')
|
||||
try:
|
||||
img_file = open(image_path.joinpath(file_path), mode='rb')
|
||||
except:
|
||||
raise HTTPException(status_code=404, detail="没有找到图片")
|
||||
media_type = mimetypes.guess_type(file_path)[0]
|
||||
img_resp = BytesIO(img_file.read())
|
||||
img_file.close()
|
||||
try:
|
||||
ori_file_name = crud.get_pic_by_path(db, file_path=file_path).file_name
|
||||
except:
|
||||
raise HTTPException(status_code=500, detail="无法连接数据库")
|
||||
return StreamingResponse(content=img_resp, media_type=media_type, headers={'Content-Disposition': f'inline; filename={ori_file_name}'})
|
||||
|
||||
|
||||
@router.post("/image", response_model=schemas.image.Image, tags=['图片'])
|
||||
async def create_pic(pic: UploadFile, db: Session = Depends(get_db)):
|
||||
image_path = Path(Path.home()).joinpath(
|
||||
'Pictures').joinpath('upload_images')
|
||||
try:
|
||||
Path.mkdir(image_path, parents=True)
|
||||
except FileExistsError:
|
||||
pass
|
||||
ext_name = pic.filename.split('.')[-1]
|
||||
file_name = f'{uuid1().hex}.{ext_name}'
|
||||
db_pic = schemas.image.ImageCreate(
|
||||
file_name=pic.filename, file_path=file_name, upload_time=str(round(int(time()*1000))))
|
||||
# 尝试存储图片文件,失败则抛出500错误
|
||||
try:
|
||||
with open(image_path.joinpath(file_name), mode='wb') as f:
|
||||
f.write(await pic.read())
|
||||
except:
|
||||
raise HTTPException(status_code=500, detail="文件存储失败")
|
||||
await pic.close()
|
||||
# 尝试存储图片信息到数据库,失败则抛出500错误并删除此前存储的图片文件
|
||||
try:
|
||||
pic_obj = crud.create_pic(db, pic=db_pic)
|
||||
return pic_obj
|
||||
except:
|
||||
image_path.joinpath(file_name).unlink()
|
||||
raise HTTPException(status_code=500, detail="无法连接数据库")
|
||||
|
||||
|
||||
# 获取给定 url 的图片的缩略图
|
||||
|
||||
@router.get('/thumbnail', tags=['图片'])
|
||||
async def get_pic_thumb(url: str, w: int):
|
||||
resp = requests.get(url)
|
||||
im = Image.open(BytesIO(resp.content))
|
||||
size = w, im.size[1]
|
||||
im.thumbnail(size)
|
||||
ext_name = im.format
|
||||
if (im.format == "JPEG"):
|
||||
ext_name = 'jpg'
|
||||
ext_name = ext_name.lower()
|
||||
pic_buffer = BytesIO()
|
||||
im.save(pic_buffer, format=im.format)
|
||||
im.close()
|
||||
resp_image = BytesIO(pic_buffer.getvalue())
|
||||
pic_buffer.close()
|
||||
return StreamingResponse(content=resp_image, media_type='image/'+im.format.lower(), headers={'Content-Disposition': 'inline; filename=image.'+ext_name})
|
||||
|
||||
# @router.get("/users/", tags=["users"])
|
||||
# async def read_users():
|
||||
# return [{"username": "Rick"}, {"username": "Morty"}]
|
||||
# @router.get("/users/me", tags=["users"])
|
||||
# async def read_user_me():
|
||||
# return {"username": "fakecurrentuser"}
|
||||
# @router.get("/users/{username}", tags=["users"])
|
||||
# async def read_user(username: str):
|
||||
# return {"username": username}
|
@ -1,5 +1,3 @@
|
||||
from ctypes import sizeof
|
||||
from turtle import width
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models, schemas
|
||||
|
Reference in New Issue
Block a user