烧瓶刷新消息原因会话不可用

时间:2019-02-18 07:32:43

标签: flask

使用官方文档中的准确代码:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        ...
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            ..
            flash('File was successfully uploaded')
            return redirect(url_for('uploaded_file', filename=filename))
    return render_template('home.html')

没有flash(),一切正常。但是添加时会导致错误该会话不可用,因为没有秘密。下面是跟踪:

> 127.0.0.1 - - [18/Feb/2019 10:16:21] "POST / HTTP/1.1" 500 -
> 127.0.0.1 - - [18/Feb/2019 10:17:16] "GET / HTTP/1.1" 200 - [2019-02-18 10:17:23,999] ERROR in app: Exception on / [POST]
> Traceback (most recent call last):   File
> "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/app.py",
> line 2292, in wsgi_app
>     response = self.full_dispatch_request()   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/app.py",
> line 1815, in full_dispatch_request
>     rv = self.handle_user_exception(e)   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/app.py",
> line 1718, in handle_user_exception
>     reraise(exc_type, exc_value, tb)   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/_compat.py",
> line 35, in reraise
>     raise value   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/app.py",
> line 1813, in full_dispatch_request
>     rv = self.dispatch_request()   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/app.py",
> line 1799, in dispatch_request
>     return self.view_functions[rule.endpoint](**req.view_args)   File "/home/dvperv/PycharmProjects/astros/app.py", line 39, in upload_file
>     flash('No file part')   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/helpers.py",
> line 410, in flash
>     session['_flashes'] = flashes   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/werkzeug/local.py",
> line 350, in __setitem__
>     self._get_current_object()[key] = value   File "/home/dvperv/PycharmProjects/astros/venv/lib/python3.6/site-packages/flask/sessions.py",
> line 101, in _fail
>     raise RuntimeError('The session is unavailable because no secret ' RuntimeError: The session is unavailable because no secret key was
> set.  Set the secret_key on the application to something unique and
> secret.
> 127.0.0.1 - - [18/Feb/2019 10:17:24] "POST / HTTP/1.1" 500 -

我已经阅读了有关此错误的几篇文章,但它们均与Flask-Session扩展有关,我不使用它

我还尝试在应用程序中添加app.secret_key = 'super secret key',但没有成功。

我应该使用Flask Session并进行适当的配置,还是有一种方法可以只使用普通的Flask flash()来在后台与会话本身一起工作。

应用配置:

app = Flask(__name__)

UPLOAD_FOLDER = ..
ALLOWED_EXTENSIONS = ..

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

if __name__ == '__main__':
app.run()

3 个答案:

答案 0 :(得分:1)

在堆栈跟踪中非常清楚地表明未设置秘密密钥。确保将密钥设置在正确的位置,例如在这里:

app = Flask(__name__)
app.secret_key = 'asrtarstaursdlarsn'

UPLOAD_FOLDER = ..

答案 1 :(得分:1)

附加的跟踪信息表明您尚未添加密钥。可能是您稍后添加了密钥,但是应用程序未与更新的代码同步。

我正在分享一个在Flask中使用纯Flash消息的基本示例。

app.py

from flask import Flask, render_template, flash

app = Flask(__name__)
app.secret_key = 'super secret'

@app.route('/')
def index():
    flash("Flashing a dummy message")
    return render_template("flash_example.html")

@app.route('/another')
def show_page_without_flash():
    return render_template("flash_example.html")

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

flash_example.html

<!DOCTYPE html>
<html>
    <head><title>Flash example</title></head>
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
        <p>Dummy paragraph</p>
    </body>
</html>

使用Flash消息(/)进行路由:

flash message example

没有Flash消息的路由(/另一个):

enter image description here

答案 2 :(得分:0)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'anystringthatyoulike'

添加密钥