4
\$\begingroup\$

I have 2 Flask apps (different projects) that work together . One implements some API which uses tokens for auth. The second one consumes the API and makes a web interface for it. Now I have a login function that sends the username and password to the API, and if correct, gets the auth token in return. Once I have the token, I save it to the session of the user and the user should now be considered as logged in/ autheticated.

Here is my login function -

def login(self):
        response = make_request(BASE_URL + 'login/', clean_data(self.data))
        if response.status_code == 200:
            session['auth_token'] = response.json().get('auth_token')
            return True
        return False

Also I am using Redis to store sessions if that matters. I have made the following login_required decorator -

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('auth_token') is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)

    return decorated_function

While it does work, I'm not sure if this is the best way to make that decorator. Any suggestions would be helpful.

\$\endgroup\$
2
\$\begingroup\$

I would suggest using:

if 'auth_token' not in session:
    ...

Since your login function suggests that auth_token is not a key in session, unless the user has logged in.

Other that that, I can see no other improvements.

\$\endgroup\$
  • \$\begingroup\$ Wouldn't it work same as if session.get('auth_token') is None: \$\endgroup\$ – utkbansal Dec 31 '15 at 4:22
  • \$\begingroup\$ @utkbansal Yes, it would, but only because dict.get implicitly returns None if the given property does not exist. And, according to the zen of Python, explicit is better than implicit. Also, I think this is more readable and intuitive. \$\endgroup\$ – Tuomas Laakkonen Dec 31 '15 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.