RuntimeError:无法访问请求外部的配置 [英] RuntimeError: cannot access configuration outside request

查看:107
本文介绍了RuntimeError:无法访问请求外部的配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误:

RuntimeError: cannot access configuration outside request

通过执行以下代码:

# -*- 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.

我正在使用 Flask-Uploads 扩展名.

这在具有以下已安装软件包的python 2.7虚拟环境中运行:

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

推荐答案

您尚未已配置Flask-Uploads扩展程序.使用 configure_uploads()函数将上传集附加到应用程序:

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,))

UploadSet()的第二个参数采用扩展名的序列.不要将文件路径传递到UploadSet;您应该使用烧瓶配置.

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.

设置UPLOADED_<name-of-your-set>_DEST,名称用大写字母表示.这是UPLOADED_CSVFILES_DEST.您还可以设置UPLOADS_DEFAULT_DEST配置.它将用作基本目录,每个集名称都有单独的子目录.

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')

这篇关于RuntimeError:无法访问请求外部的配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆