django drf 反序列化上传图片
2021-04-19 19:28
标签:nbsp hunk import 文件夹 返回 data image serialize pattern 由于之前限制图片的后缀名,所以jfif格式上传不成功 django drf 反序列化上传图片 标签:nbsp hunk import 文件夹 返回 data image serialize pattern 原文地址:https://www.cnblogs.com/u-damowang1/p/12264664.html
#上传图片的类型
ALLOWED_IMG_TYPE = [‘jpg‘,‘png‘,‘PNG‘]
#上传图片的地址
UPLOAD_ADDRESS = ‘static/upload/‘
STATIC_URL = ‘/static/‘
#配置静态文件夹
STATICFILES_DIRS = [
os.path.join(BASE_DIR,‘static‘),
]
from django.urls import path
from . import views
#二级路由
urlpatterns = [
path(‘goods/‘, views.GoodsView.as_view()),
]
#商品的反序列化
class GoodUnSerializer(serializers.Serializer):
#商品名称约束
name = serializers.CharField(max_length=32)
#商品价格约束
price = serializers.DecimalField(max_digits=9,decimal_places=2)
#商品分类约束
cate_id = serializers.IntegerField()
#商品图片约束
img = serializers.CharField(max_length=255)
def create(self, validated_data):
#将获取的字典类型打散
return models.Goods.objects.create(**validated_data)
#商品
class GoodsView(APIView):
def post(self, request):
name = request.POST.get(‘name‘, ‘‘).strip()
price = request.POST.get(‘price‘, 0)
cate_id = request.POST.get(‘cate_id‘)
data = {
‘name‘:name,
‘price‘:price,
‘cate_id‘:cate_id
}
img = request.FILES.get(‘img‘)
if img:
#获取后缀名
ext = img.name.split(‘.‘)[-1]
#如果上传图片的后缀名不在配置的后缀名里返回格式不允许
if ext not in settings.ALLOWED_IMG_TYPE:
return Response({
"status":205,
"msg":"格式不允许",
"data":‘‘
})
# path = ‘‘
#新的文件名
newfielname = datetime.now().strftime(‘%Y%m%d%H%M%S‘) + str(random.randint(10000,99999)) + ‘.‘ + ext #采用时间和随机数
path = settings.UPLOAD_ADDRESS + newfielname
with open(path,‘wb‘) as f: #二进制写入
for i in img.chunks():
f.write(i)
data[‘img‘] = newfielname
#入库反序列化添加
obj = GoodUnSerializer(data=data)
if obj.is_valid():
obj.save()
print(obj.errors)
return Response({
‘status‘:200,
‘msg‘:‘添加成功‘,
‘data‘:‘‘
})
return Response({
‘status‘:201,
‘msg‘:‘添加失败‘,
‘data‘:‘‘
})