Reputation: 1281
I have below codes written in python in Django. Since I am new to Django and python, I have a hard time understanding below code. What makes me understand hard is that the function process(f)
inside in the for-loop. why does it have to be inside the for-loop?
def Upload(request):
for count,x in enumerate(request.FILES.getlist("files")):
def process(f):
with open('/Users/sclee/PycharmProjects/uploadFile/bin/upload/media/file_' + str(count),'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
process(x)
return HttpResponse("File(s) uploaded")
Upvotes: 0
Views: 59
Reputation: 51988
No, you don't have to. You can put it anywhere, even outside of the python file in which you are uploading files. Lets say, you have it handle_upload.py
file, in which you have written process
function to handle uploads. Then you can use it like this:
# in handle_upload.py
def process(f, count):
with open('/Users/sclee/PycharmProjects/uploadFile/bin/upload/media/file_' + str(count)+'.txt','wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
# inside views.py
from .handle_upload import process # assuming handle_upload.py is in same directroy as this view file
def Upload(request): # use snake_case for defining functions. Please read PEP-8 Style guide
for count,x in enumerate(request.FILES.getlist("files")):
process(x, count)
return HttpResponse("File(s) uploaded")
Upvotes: 1