How do I know if request.FILES is empty?

Asked

Viewed 833 times

3

I have a code on Django where I want to upload a file from a form.

At a given precise moment check if the index exists "arquivo" within the variable request.FILES

I did it using the method has_key as follows (do not notice if the code is ugly, because I am a beginner in the 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, rather than checking whether a specific index exists, I would like to know what is the best way to check whether request.FILES is empty.

I had devised two ways to try to do 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 don’t know if this is appropriate. I’m learning the language now and I don’t want to start by sniffing.

That is: Is there any better way to check whether request.FILES is empty?

2 answers

3


Like the attribute FILES of 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!" 
  • 2

    It’s a dictionary, actually, but it’s not really a dict - and yes a MultiValueDict. For a single file it makes no difference, but if the form has some field <input type="file" multiple> things get... a little confused! : P For the purpose of the answer, it makes no difference, however.

1

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

Could specifically check 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'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.