afidegnum February 2016

UnboundLocalError: local variable 'filename' referenced before assignment

I m trying to get the file names and display the list, i am having the following error, of UnboundLocalError: local variable 'filename' referenced before assignment

here is the code, i m working on and it seems the loop is not properly set.

@media.route('/uploadajax', methods=['POST'])
def upldfile():
    if request.method == 'POST':
        files = request.files.getlist('file[]')
        for f in files:
            if f and allowed_file(f.filename):
                filename = secure_filename(f.filename)
                updir = os.path.join(basedir, 'upload/')
                f.save(os.path.join(updir, filename))
                file_size = os.path.getsize(os.path.join(updir, filename))
            else:
                app.logger.info('ext name error')
                return jsonify(error='ext name error')
        return jsonify(name=filename, size=file_size)

How do I fix the loop issue?

Answers


Andriy Ivaneyko February 2016

Adding lines below before for loop would fix your problem:

files = request.files.getlist('file[]')
if not files:
    return jsonify(error='Please add files')
for f in files:
    # for loop body


keksnicoh February 2016

As seen in answer of @Andriy Ivaneyko, the problem is that you may have an empty list of files here. You could create a list which contains validation result to enable detailed error reporting in frontend.

@media.route('/uploadajax', methods=['POST'])
def upldfile():
    if request.method == 'POST':
        files = request.files.getlist('file[]')
        my_json_stuff = []
        for f in files:
            if f and allowed_file(f.filename):
                filename = secure_filename(f.filename)
                updir = os.path.join(basedir, 'upload/')
                f.save(os.path.join(updir, filename))
                file_size = os.path.getsize(os.path.join(updir, filename))
                my_json_stuff.append({'name': filename, 'size': file_size})
            else:
                app.logger.info('ext name error')
                my_json_stuff.append({'error': 'ext name error'})

        return jsonify(my_json_stuff)

Post Status

Asked in February 2016
Viewed 2,488 times
Voted 12
Answered 2 times

Search




Leave an answer