Disable user loading for some routes for app using Flask-Security

An application with Flask-Security makes a request to the database for the authenticated user for each route, but sometimes it’s not necessary. Here is a way how to disable it with a decorator and custom UserDatastore.

def no_user(endpoint_view):
    endpoint_view._no_user = True

    @wraps(endpoint_view)
    def decorated(*args, **kwargs):
        return endpoint_view(*args, **kwargs)

    return decorated

@collect_blueprint.route('/some-route', methods=['GET'])
@no_user
def some-route():
	return ''


class MyUserDataStore(MongoEngineUserDatastore):

    def check_no_user(self):
        if request.endpoint in current_app.view_functions:
            view = current_app.view_functions[request.endpoint]
            return hasattr(view, '_no_user')

    def get_user(self, identifier):
        if self.check_no_user():
            return

        return super(MyUserDataStore, self).get_user(identifier)

    def find_user(self, **kwargs):
        if self.check_no_user():
            return

        return super(MyUserDataStore, self).find_user(**kwargs)

    def find_role(self, role):
        if self.check_no_user():
            return

        return super(MyUserDataStore, self).find_role(role)
comments powered by Disqus