I impemented today https://pypi.python.org/pypi/flask-htpasswd/ on my site and I'm getting KeyError: u'FLASK_AUTH_REALM' error. What I did was putting app.config's before Class so it looks like here:
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):
And here's an error that I'm getting
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'
You do not show the complete code. I guess you want to declare the Pogom class which derive from Flask class, then declare an instance from Pogom, and execute pogom.run.
According to the exception stack, I think missing FLASK_AUTH_REALM key in app.config.
Why the FLASK_AUTH_REALM missing?
First, the flask_htpasswd extension will set the default value for FLASK_AUTH_REALM in init_app function.
But you declare one new class, and may be instance one app from Pogom and app.run. the flask_htpasswd just initialize the old app which is the instance Flask, and the new app does not have proper FLASK_AUTH_REALM key in config.
So, I try to show some code like below:
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()
Related
I'm kind of new to using flask, and I want to cache the result of a function that reads pickled data. I use memoize function from flask_cache as follows:
in model_chacher.py:
from flask_cache import Cache
import pickle
model_cache = Cache(config={'CACHE_TYPE': 'simple'})
class ModelCacher():
#model_cache.memoize(50)
def get_model(self, customer_ID):
with open('/path/to/data.pickle', 'rb') as tf:
model_args = pickle.load(tf)
trained_classifier = model_args[0]
return trained_classifier
in flask_compose.py:
from flask import Flask
from controllers.topic import controller as topic_controller
from models.modelcache.model_chacher import model_cache
app = Flask(__name__)
model_cache.init_app(app)
app.register_blueprint(topic_controller.topic_controller_blueprint)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=80, debug=True)
and I call ModelCacher.get_model(customer_ID) in topic_controller:
from models.modelcache.model_chacher import ModelCacher
...
trained_classifier = ModelCacher.get_model(cls_str)
...
and after running flask_compose.py and sending a request I get the following result:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/controllers/topic/controller.py", line 20, in classify
return ModelCacher.get_model(cls_str)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 528, in decorated_function
cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 393, in make_cache_key
**kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 434, in _memoize_kwargs_to_args
elif abs(i-args_len) <= len(argspec.defaults):
TypeError: object of type 'NoneType' has no len()
and my question is: how to properly set up my cache? any help is greatly appreciated.
EDIT: WHAT SOLVED MY PROBLEM:
as #stamaimer pointed out, I create and instance of my ModelCacher and that solved the problem, also I used cached from flask_cache.Cache instead of memoize.
The get_model method your defined is a instance method instead of a class method. You use ModelCacher.get_model(cls_str) when call the method. Try to call it with ModelCacher().get_model(cls_str). Or you can just defined it as a global function.
In my new job we are using the Flask framework (I'm newbie in the Flask). Every view is the child of MethodView. The code looks like this:
from flask import render_template
from flask.views import MethodView
class HelloWorldPage(MethodView):
def get(self):
return render_template('helloworld.html')
def configure_routing(app):
app.add_url_rule('/<lang>/helloworld', view_func=HelloWorldPage.as_view('helloworld'))
Of course, configure_routing(app) from helloworld.py is called in appropriate place. Now, my question is if it's possible to get <lang> from route? When I write get(self, lang) it throws an exception TypeError: get() takes exactly 2 arguments (1 given), when I create a method called helloworld(lang), it throws me that method get is not implemented and so on. Thank you very much. Bye
Edit:
traceback to get(self, lang)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1994, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 149, in dispatch_request
return meth(*args, **kwargs)
TypeError: get() takes exactly 2 arguments (1 given)
I tried the same
from flask import Flask, render_template
from flask.views import MethodView
app = Flask(__name__)
class HelloWorldPage(MethodView):
def get(self, lang):
return render_template('HelloWorld.html', language=lang)
app.add_url_rule('/<lang>/helloworld', view_func=HelloWorldPage.as_view('helloworld'))
if __name__ == '__main__':
app.run()
response below
comment from flask.views
METHODVIEW :
Like a regular class-based view but that dispatches requests to
particular methods. For instance if you implement a method called
:meth:get it means it will respond to 'GET' requests and
the :meth:dispatch_request implementation will automatically
forward your request to that. Also :attr:options is set for you
automatically::
Did you restrart the service after changing get(self) to get(self, lang) ?
if you did then please check the application init file where you import HelloWorldPage view and make sure
app = Flask(__name__)
## IMPORT YOUR APP VIEWS
## THEN CONFIGURE THE ROUTINGS
def configure_routing(app):
app.add_url_rule('/<lang>/helloworld', view_func=HelloWorldPage.as_view('helloworld'))
Following this example I integrated Flask admin with some already created peewee models. Everything looks great until I try the list view of the admin interface, but first some context:
The Code
The important part of the app.py file:
def create_app(config_object=DevConfig):
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
return app
def register_extensions(app):
"""Register Flask extensions."""
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
admin = Admin(app, name=__name__, template_mode='bootstrap3')
__add_admin_views(admin)
return None
def __add_admin_views(admin):
admin.add_view(ClientAdmin(entities.Client))
return None
The injection of the database object in the package initialization file:
def persistence_config(binder):
db_user = "postgres"
db_name = "MY_DB_NAME"
db_password = "MY_PASS"
db_host = "127.0.0.1"
db_port = 5432
db = PooledPostgresqlExtDatabase(
database=db_name,
user=db_user,
host=db_host,
password=db_password,
max_connections=8,
stale_timeout=300,
register_hstore=False)
binder.bind(Database, lambda: db)
The Error
This happens when I try to request the list of clients (http://127.0.0.1:5000/admin/client/):
Traceback (most recent call last):
File "MY_ENV_PATH/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "MY_ENV_PATH/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "MY_ENV_PATH/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "MY_ENV_PATH/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/base.py", line 68, in inner
return self._run_view(f, *args, **kwargs)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/base.py", line 367, in _run_view
return fn(self, *args, **kwargs)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/model/base.py", line 1738, in index_view
view_args.search, view_args.filters)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/contrib/peewee/view.py", line 353, in get_list
query = self.get_query()
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/contrib/peewee/view.py", line 328, in get_query
return self.model.select()
File "MY_ENV_PATH/lib/python2.7/site-packages/peewee.py", line 4458, in select
query = SelectQuery(cls, *selection)
File "MY_ENV_PATH/lib/python2.7/site-packages/peewee.py", line 2696, in __init__
self.require_commit = self.database.commit_select
AttributeError: 'function' object has no attribute 'commit_select'
I found the issue in my code and it was related to the way i am injecting the Database object into models. I had to use the constructor binding instead of the normal bind as i was binding a lambda function:
binder.bind_to_constructor(Database, lambda: db)
I'm building a website using Flask in which I also use Websockets using Flask-socketIO, but there's one thing I don't understand.
I built a chat-functionality. When one user sends a message I use websockets to send that message to the server, after which I emit the message to the other user from within that same call:
#socketio.on('newPM', namespace='/test')
#login_required_with_global
def io_newMessage(theJson):
emit('message', {'message': theJson['message']}, room=str(theJson['toUserId']))
But let's say that I want to emit a message to a user when a file was saved. This means that I need to emit a message from within the view in which the file is POSTed. So according to the flask_socketio docs I can add a namespace in the emit. So I wrote this:
#app.route('/doc', methods=['POST'])
#login_required
def postDoc():
saveDocument(request.files['file'], g.user.id)
emit('my response', {'data': 'A NEW FILE WAS POSTED'}, room=current_user.id, namespace='/test')
return jsonify({'id': str(doc.id)})
But seeing the stacktrace below there still is a problem with the namespace; werkzeug has an AttributeError: 'Request' object has no attribute 'namespace'.
Does anybody know what I'm doing wrong here? Or is this a bug in flask_socketio? All tips are welcome!
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "/home/vg/app/views.py", line 768, in emitNotificationCount
emit('menuInit', emitJson, room=current_user.id, namespace='/test')
File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 444, in emit
return request.namespace.emit(event, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'Request' object has no attribute 'namespace'
Quoting from Miguel Grinberg's response on an open issue page on the Flask-SocketIO GitHub:
When you want to emit from a regular route you have to use
socketio.emit(), only socket handlers have the socketio context
necessary to call the plain emit().
So as an example:
from flask_socketio import SocketIO
app = Flask(__name__)
app.config.from_object('config')
socketio = SocketIO(app)
#app.route('/doc', methods=['POST'])
def postDoc():
saveDocument(request.files['file'], g.user.id)
socketio.emit('my response', {'data': 'A NEW FILE WAS POSTED'}, room=current_user.id)
return jsonify({'id': str(doc.id)})
I am building a basic app with Flask: it has a unique route that requests just a token authentication, i.e. if the token provided in the headers is correct, then the request is satisfied. To do so, I installed both Flask and Flask-Security. This is a snippet of my app:
from flask import Flask
from flask.ext.security import auth_token_required
from flask.ext.security import Security
app = Flask(__name__)
app.config['SECURITY_TOKEN_AUTHENTICATION_KEY'] = 'mytoken'
security = Security(app)
#app.route('/myurl')
#auth_token_required
def myrequest():
return 'OK'
if __name__ == '__main__':
app.run(debug=True)
I test it by running:
$ curl -H 'Authorization: Token token="mytoken"' localhost:5000/myurl
or even:
$ curl localhost:5000/myurl
However, I get the following error:
Traceback (most recent call last):
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 113, in decorated
if _check_token():
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 50, in _check_token
header_key = _security.token_authentication_header
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 24, in <lambda>
_security = LocalProxy(lambda: current_app.extensions['security'])
KeyError: 'security'
Do you know where the error lies? Is it in the app or in some conflicts among the Flask libraries?
EDIT: added Security(app) initialization
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)