KeyError:u'FLASK_AUTH_REALM'

时间:2017-06-21 11:07:42

标签: python authentication flask

我今天在我的网站上发布了https://pypi.python.org/pypi/flask-htpasswd/,我收到了KeyError:u'FLASK_AUTH_REALM'错误。我所做的是把app.config放在Class之前,所以它看起来像这样:

from .utils import now, dottedQuadToNum, get_blacklist
log = logging.getLogger(__name__)
compress = Compress()
import flask
from flask_htpasswd import HtPasswdAuth

app = flask.Flask(__name__)
app.config['FLASK_HTPASSWD_PATH'] = 'C:/.htpasswd'
app.config['FLASK_SECRET'] = 'Hey Hey Kids, secure me!'
htpasswd = HtPasswdAuth(app)


class Pogom(Flask):

    def __init__(self, import_name, **kwargs):

这是我得到的错误

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_htpasswd.py", line 205, in decorated
    return self.auth_failed()
  File "C:\Python27\lib\site-packages\flask_htpasswd.py", line 159, in auth_failed
    current_app.config['FLASK_AUTH_REALM']
KeyError: u'FLASK_AUTH_REALM'

1 个答案:

答案 0 :(得分:0)

您没有显示完整的代码。我想你想要声明从Pogom类派生的Flask类,然后从Pogom声明一个实例,并执行pogom.run

根据异常堆栈,我认为FLASK_AUTH_REALM中缺少app.config密钥。

为什么FLASK_AUTH_REALM丢失?

首先,flask_htpasswd扩展名将在FLASK_AUTH_REALM函数中设置init_app的默认值。

但是您宣布了一个新课程,可能是来自Pogomapp.run的实例一个应用。 flask_htpasswd只是初始化旧应用程序,即实例Flask,新应用程序在配置中没有正确的FLASK_AUTH_REALM键。

所以,我尝试显示如下代码:

from flask import Flask
from flask_htpasswd import HtPasswdAuth


class Pogom(Flask):
    def __init__(self, import_name, **kwargs):
        # missing some special code
        super(Pogom, self).__init__(import_name, **kwargs)


htpasswd = HtPasswdAuth()


def create_app():
    app = Pogom(__name__)
    app.config['FLASK_HTPASSWD_PATH'] = 'C:/.htpasswd'
    app.config['FLASK_SECRET'] = 'Hey Hey Kids, secure me!'
    htpasswd.init_app(app)
    return app


if __name__ == '__main__':
    app = create_app()

    # just for demonstration
    @app.route('/')
    @htpasswd.required
    def index():
        return "Hello"


    app.run()