1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import osfrom uuid import uuid4 from flask_restful import Resource, reqparse from werkzeug.datastructures import FileStoragefrom app.config import Config from .models import *def img_upload(img): if not img: return None # 将图片名按照 . 进行切分, 找到最后一个元素,也就是 文件的后缀名 end_name = img.filename.rsplit('.')[-1] # 通过文件的后缀名判断 身份为 合法的 图片 if end_name not in ['jpg', 'png', 'gif', 'jpeg']: return None filename = str(uuid4()) + '.' + end_name # 为了生成一个不重复的 文件名 img_path = os.path.join(Config.STATIC_ROOT, filename) # 将路径和文件名拼接在一起,方便保存文件 img.save(img_path) # 将图片对象保存到 本地 return filenameclass NewsView(Resource): def post(self): # 1. 创建解析参数的对象 parser = reqparse.RequestParser() # 2. 指明需要解析的参数 parser.add_argument('title', type=str, location='form', required=True) parser.add_argument('img', type=FileStorage, location='files') # 3. 获取具体的参数 args = parser.parse_args() title = args.get('title') img = args.get('img') # 利用自定义函数,将图片保存到本地 filename = img_upload(img) # 4. 创建对象, 注意:图片存储的只是 从media之后的 图片路径 news = News(title=title, img=filename) # 5. 添加到 事务中 db.session.add(news) # 6. 提交事务 try: db.session.commit() except: return { 'msg': '添加失败' }, 500 # 7. 返回响应 return { 'id': news.id, 'title': news.title, 'img': news.img }, 201
|