Django Rest Framework 내에서 업로드 된 파일의 HTTP 요청을 처리하는 방법을 아는 데 어려움이 있습니다. create
내 views.py 의 끝점 :
def create(self, request):
file_iobytes = request.FILES["file"].file
self.zipping(file_iobytes)
serializer = FileSerializer(data=request.data) # converts to JSON
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def zipping(self, file):
# Create a buffer to write the zipfile into
zip_buffer = io.BytesIO()
# Create the zipfile, giving the buffer as the target
with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
#file.seek(0)
zip_file.write(file)
file.close()
models.py
class File(models.Model):
file = models.FileField(upload_to='Myfiles/')
...
def __str__(self):
return self.file.name
serializers.py
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = '__all__'
read_only_fields = ('timestamp',)
내 의도는 :
요청을 사용하여 zip 파일을 생성하려면 어떻게해야합니까 (올바른 접근 방식입니까)?
설명이 자명하기를 바랍니다. :)
import hashlib
from rest_framework.decorators import api_view
from rest_framework.response import Response
def generate_sha1(file_pointer):
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536 # lets read stuff in 64kb chunks!
sha1 = hashlib.sha1()
while True:
data = file_pointer.read(BUF_SIZE)
if not data:
break
sha1.update(data)
return sha1.hexdigest()
def generate_zip(model_instance):
source_file = f'{model_instance.file.name}'
dest_file = f'{source_file}.zip'
zipfile.ZipFile(dest_file, mode='w').write(source_file)
return dest_file
def re_assign_files(model_instance, dest_file):
model_instance.file.delete() # deletes the uploaded file
model_instance.file = dest_file # mapping the generated zip file
model_instance.save() # saving the model instance
@api_view(http_method_names=['GET', 'POST'])
def foo_api(request):
if request.method == 'GET':
return Response({'message': 'this is get method'})
else:
serializer = FileSerializer(data=request.data)
serializer.is_valid(True) # validating the data
model_instance = serializer.save() # saving the data into database
hash_sha1 = generate_sha1(serializer.validated_data['file']) # generates the SHA1 value
dest_file = generate_zip(model_instance) # generates zip file
re_assign_files(model_instance, dest_file)
return Response({'sha1': hash_sha1, 'data': serializer.data})
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다