Question

I try to use flask login in may app:

My controller:

@app.route("/process_log", methods=['POST'])
def process_login():
    filled_form = LoginForm(request.form)
    if filled_form.validate():
        phone = filled_form.phone.data
        password = filled_form.password.data
        if User.phone_exists(phone) and User.pass_match(phone, password):
            user = User.get_by_phone(phone)
            login_user(user.get_id)
            return redirect(url_for("index"))
        else:
            return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
    else:
        return render_template("home.html", form = filled_form)

and I have some class with defined functions which required for API of flask login

My User class:

from pymongo import MongoClient
from bson.objectid import ObjectId


class User():
    client = MongoClient()
    db = client['test']
    col = db['user']
    user_id = None

    def __init__(self, dic):
        self.dic = dic

    def is_authenticated():
        return True

    def is_anonymous():
        return False

    def is_active():
        return True

    def get_id(self):
        return unicode(str(self.user_id))

    def save(self):
        self.user_id = self.col.insert(self.dic)
        print "Debug:" + str(self.user_id)


    @staticmethod
    def _get_col():
        client = MongoClient()
        db = client['test']
        col = db['user']
        return col

    @staticmethod
    def phone_exists(phone):
        col = User._get_col()
        if col.find_one({'phone': phone}) != None:
            return True
        else:
            return False

    @staticmethod
    def pass_match(phone, password):
        col = User._get_col()
        if col.find_one({'phone': phone})['password'] == password:
            return True
        else:
            return False

    @staticmethod
    def get(userid):
        col = User._get_col()
        return col.find_one({'_id':userid})

    @staticmethod
    def get_by_phone(phone):
        col = User._get_col()
        dic = col.find_one({'phone': phone})
        print dic['password']
        return User(dic)

As you see function is_active is defined(Note:I also tried to pass refference with self)

But I still have this error AttributeError: 'function' object has no attribute 'is_active'

I am sorry for too much code here, but it should be pretty straightforward.

Note: I am using mongodb for my project.

Please help me to find my error. Thank you too much

One more thing: Should I provide login_user(....) with Id or with my user object?

Was it helpful?

Solution

You must sent to login_user User instance (not id), see: https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576.

So next code must work:

user = User.get_by_phone(phone)
login_user(user)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top