我今天在我的网站上发布了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'
答案 0 :(得分:0)
您没有显示完整的代码。我想你想要声明从Pogom
类派生的Flask
类,然后从Pogom
声明一个实例,并执行pogom.run
。
根据异常堆栈,我认为FLASK_AUTH_REALM
中缺少app.config
密钥。
为什么FLASK_AUTH_REALM
丢失?
首先,flask_htpasswd扩展名将在FLASK_AUTH_REALM
函数中设置init_app
的默认值。
但是您宣布了一个新课程,可能是来自Pogom
和app.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()