Geen omschrijving

views.py 2.8KB

    # -*- coding: utf-8 -*- from django.core.files.storage import default_storage from django.http import JsonResponse from rest_framework import viewsets from account.models import LensmanInfo from photo.models import PhotosInfo from photo.serializers import PhotosInfoSerializer import os # [How to do a PUT request with curl?](http://stackoverflow.com/questions/13782198/how-to-do-a-put-request-with-curl) # Unfortunately, the -T is no substitute for -X PUT if you want to specify parameters with -d or -F. # -T sends the content of a file via PUT. To achieve the GET after a redirect, add the parameter --location # # -F, --form <name=content> # (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data # using the Content-Type multipart/form-data according to RFC 2388. This enables uploading of binary files etc. To force the # 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file # name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, # while the < makes a text field and just get the contents for that text field from a file. # # curl -X POST -F lensman_id=123 -F session_id=456 -F photo_id=789 -F photo=@7056288a9ddf2db294cf50a943920989.jpg;filename=789 http://xfoto.com.cn/api/photos/upload def upload_photo(request): lensman_id = request.POST.get('lensman_id', '') session_id = request.POST.get('session_id', '') photo_id = request.POST.get('photo_id', '') photo = request.FILES.get('photo', '') if not (lensman_id and session_id and photo_id and photo): return JsonResponse({ 'status': 400, 'message': u'参数错误', }) try: LensmanInfo.objects.get(lensman_id=lensman_id) except LensmanInfo.DoesNotExist: return JsonResponse({ 'status': 400, 'message': u'参数错误', }) _, extension = os.path.splitext(photo.name) photo_path = 'photo/{0}/{1}/{2}{3}'.format(lensman_id, session_id, photo_id, extension) if default_storage.exists(photo_path): default_storage.delete(photo_path) default_storage.save(photo_path, photo) photo, created = PhotosInfo.objects.get_or_create( lensman_id=lensman_id, session_id=session_id, photo_id=photo_id, photo_path=photo_path ) return JsonResponse({ 'status': 200, 'message': u'照片上传成功', 'data': photo.data, }) class PhotoInfoViewSet(viewsets.ModelViewSet): queryset = PhotosInfo.objects.all().order_by('-created_at') serializer_class = PhotosInfoSerializer