How to know if request.FILES is empty?

3

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?

    
asked by anonymous 05.02.2015 / 18:48

2 answers

3

As the attribute FILES of < a href="https://docs.djangoproject.com/en/1.7/ref/request-response/#httprequest-objects"> HttpRequest is a dictionary, you can check it in several ways:

files = {} 
if not files:
    print "Dicionario vazio!"

if not bool(files):
    print "Dicionario vazio!"

if len(files) == 0:
    print "Dicionario vazio!" 
    
05.02.2015 / 19:22
1

Checking if any file is being uploaded can be used as you put it in your example if request.FILES

I could specifically check it can also be done this way:

try:
    request.FILES['arquivo']
except KeyError:
    print 'arquivo não enviado'
else:
    pass
    # faz upload

or

if request.FILES.get('arquivo', False):
    pass
    # faz upload
else:
    print 'arquivo não enviado'
    
05.02.2015 / 21:33