I have a code in Django
where I want to upload a file from a form.
At any given moment, I need to check if the index "arquivo"
exists within the variable request.FILES
I did this using the has_key
method as follows (do not notice if the code is ugly since I am a beginner in python
):
import os
def upload(request):
data = {}
if request.method == 'POST':
if request.FILES.has_key('arquivo'):
files = request.FILES['arquivo']
path = 'upload'
if not os.path.exists(path):
os.makedirs(path)
upload_path = path + '/' + files.name;
with open(upload_path, 'w') as upload:
upload.write(files.read())
data["teste"] = "dados enviados"
else:
data["teste"] = "arquivo não preenchido"
else:
data["teste"] = "não enviado"
return render(request, 'upload.html', data)
However, instead of checking if a specific index exists, I'd like to know what is the best way to check if request.FILES
is empty.
I had worked out two ways to try this:
1) example:
if request.FILES:
#faça alguma coisa
2) example:
if len(request.FILES) is not 0:
#faça alguma coisa
But I do not know if this is appropriate. I'm learning language now and I do not want to start playing tricks.
That is: Is there any better way to check if request.FILES
is empty?