Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeError: cannot access configuration outside request

Tags:

python

flask

I got following error:

RuntimeError: cannot access configuration outside request

from executing following code:

# -*- coding: utf-8 -*-

from flask import Flask, request, render_template, redirect, url_for
from flaskext.uploads import UploadSet, configure_uploads, patch_request_class

app = Flask(__name__)
csvfiles = UploadSet('csvfiles', 'csv', "/var/uploads")

@app.route("/")
def index():
    return "Hello World!"

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'csvfile' in request.files:
        filename = csvfiles.save(request.files['csvfile']) # the error occurs here!
        return redirect(url_for('index'))
    return render_template('upload.html')

if __name__ == "__main__":
    app.run(debug=True)

I don't understand the error message itself and i don't know how to solve the problem. I read the official documentation, and it seems i have to do some configuration (where to store the uploads), but i don't know how to do it the right way.

I'm using the Flask-Uploads extension.

This is running in a python 2.7 virtual environment with the following installed packages:

Flask==0.10.1
Flask-Uploads==0.1.3
Jinja2==2.7.2
MarkupSafe==0.23
Werkzeug==0.9.4
argparse==1.2.1
itsdangerous==0.24
wsgiref==0.1.2
like image 441
tector Avatar asked May 14 '14 09:05

tector


1 Answers

You haven't configured the Flask-Uploads extension. Use the configure_uploads() function to attach your upload sets to your app:

from flaskext.uploads import UploadSet, configure_uploads

app = Flask(__name__)
app.config['UPLOADED_CSVFILES_DEST'] = '/var/uploads'
csvfiles = UploadSet('csvfiles', ('csv',))
configure_uploads(app, (csvfiles,))

The second argument to UploadSet() takes a sequence of extensions. Don't pass in the file path to an UploadSet; you would use your Flask configuration instead.

Set UPLOADED_<name-of-your-set>_DEST, where the name is uppercased. Here that's UPLOADED_CSVFILES_DEST. You can also set a UPLOADS_DEFAULT_DEST configuration; it'll be used as a base directory, with separate subdirectories for each set name.

Alternatively, that 3rd parameter can be a callable:

configure_uploads(app, (csvfiles,), lambda app: '/var/uploads')
like image 70
Martijn Pieters Avatar answered Oct 15 '22 23:10

Martijn Pieters