Google App Engine get_current_user always return N

2019-07-28 03:08发布

问题:

here's my code

 def subscribe_current_user(self):
        user1 = SocialNodeSubscription(parent=self.key)
        user1.subscribed = True
        current_user = users.get_current_user()
        logging.error(current_user)
        if current_user:
            user1.user=current_user
        else:
            raise users.UserNotFoundError

        user1.put()

The problem is that get_current_user returns None even if i'm logged in. It stores a None in the field user1.user and it prints a None in the log console.

How can i solve that?

回答1:

Do you have login: required defined in app.yaml for your handler or have you provided a login url using users.create_login_url() so that the user can explicitly login.

Even if you are logged into google somewhere, users.get_current_user() won't return a user object.



回答2:

I have seen a lot of similar questions.

It helps to think of this line differently...

user = users.get_current_user()

This line doesn't search high and low in your browser and cache and retrieve whatever info and put it into a nice user object; it simply checks if an user is logged in to the app using the users class. Which means if you did not have the user logged with the users class, chances are this line of code won't do what you want it to do.

The important codes that should usually follow a get_current_user() method:

if user:
        greeting = ('Welcome, %s! (<a href="%s">sign out</a>)' %
                    (user.nickname(), users.create_logout_url('/')))
    else:
        greeting = ('<a href="%s">Sign in or register</a>.' %
                    users.create_login_url('/'))

self.response.out.write('<html><body>%s</body></html>' % greeting)


回答3:

I believed, you surely importing this,

from google.appengine.api import users

And also, Are you really authenticating django's 'User' model at the time of login?