【问题标题】:Python flask flash message exception remains after restarting重启后Python烧瓶闪烁消息异常仍然存在
【发布时间】:2013-10-22 18:17:28
【问题描述】:

我正在制作一个小烧瓶应用程序,其中有这样的东西:

@app.route('/bye')
def logout():
    session.pop('logged_in', None)
    flash('Adiós')
    return redirect('/index')

不用说,当我运行应用程序并导航到“/再见”时,它给了我一个 UnicodeDecodeError。好吧,现在它在扩展基本模板(呈现消息)的每个页面上都给了我相同的 unicodedecodeerror,即使在重新启动应用程序之后也是如此。尽管在源代码中删除了闪存,但始终使用相同的 dump()。我能想到的都是什么废话?请帮忙。

我不得不重新启动我的计算机来清除愚蠢的会话缓存之类的。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我认为 flash() 实际上创建了一个名为 session['_flashes'] 的会话。请参阅此代码here。因此,您可能必须:

    clear/delete the cookie 
    

    session.pop('_flashes', None)
    

    【讨论】:

    【解决方案2】:

    Flask flashing 将消息存储在会话 cookie 中,直到它们成功“使用”。 如果您在这种情况下收到 UnicodeDecodeError (https://wiki.python.org/moin/UnicodeDecodeError),则不会消耗消息,因此您会一次又一次地收到错误消息。

    我的解决方案是从浏览器中删除 cookie

    由于我在使用本地化时遇到问题,我现在通过安装我的翻译对象解决了这个问题:

    trans = gettext.GNUTranslations(...)
    trans.install(unicode=True)
    

    在我的 python 源文件中使用 UTF-8 编码,在翻译文件 (.pot) 中使用 "Content-Type: text/plain; charset=UTF-8\n"

    【讨论】:

      【解决方案3】:

      您使用的是非 ascii 字符串“adiós”,因此您需要确保 python 将字符串处理为 unicode,而不是 ascii。

      将此添加到您的 python 文件的标题中。这将告诉编译器您的文件包含 utf8 字符串

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      

      所以你的代码会是这样的:

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      
      
      from flask import Flask
      app = Flask()
      
      @app.route('/bye') 
      def logout():
          session.pop('logged_in', None)
          flash('Adiós')
          return redirect('/index')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 2020-10-09
        • 2021-12-01
        相关资源
        最近更新 更多