Django App Engine: AttributeError: 'AnonymousU

2019-04-25 08:12发布

问题:

I am using djangoappengine. When I try create a new user, authenticate that user, and log them in, I get the following error AttributeError: 'AnonymousUser' object has no attribute 'backend'.

My code is simple and looks like:

user = User.objects.create_user(username, username, password)
user.set_password(password)
user.save()

user = django.contrib.auth.authenticate(username=username, password=password)
django.contrib.auth.login(request, user)

I only get the following error on production and only occasionally:

web req_create: 'AnonymousUser' object has no attribute 'backend'
Traceback (most recent call last):
  File "/base/data/home/apps/s~XXXXX/1.356802202883392818/XXXX/XXX.py", line 332, in req_create
    login(request, user)
  File "/base/data/home/apps/s~XXXXX/1.356802202883392818/django/contrib/auth/__init__.py", line 82, in login
    request.session[BACKEND_SESSION_KEY] = user.backend
AttributeError: 'AnonymousUser' object has no attribute 'backend'

I am not sure, but I have a bad feeling that this exception is due to the high replication data store and its eventual consistency. I think that authenticate() saves the user value and that login() does a query but the user value has not yet propagated into the HRDS. Can anyone confirm this to be true? If so, how would it be fixed?

回答1:

When you save the user it will be not activate automatically. Please check the link for AnonymousUser which says how your user become AnonymousUser.

So you have to set all items which may be make your user as AnonymousUser. Before authenticate please check user.is_anonymous().



回答2:

Had the same problem. But the problem was that the username was to long and it was truncated to 30 characters. Found the answer here:

Django Register Form 'AnonymousUser' object has no attribute 'backend'



回答3:

That happens when user was not authenticated. Be sure that you are using same field for loging Backend... for example I am loging with email (Backend that uses email and password) so

django.contrib.auth.authenticate(username=username, password=password)

if for me

django.contrib.auth.authenticate(username=email, password=password)

The backend is here: http://www.micahcarrick.com/django-email-authentication.html



回答4:

If you are using replication in your database and happen to be reading from Read replica while writing to your master/default database, then if there is a replication lag that could also cause this. You will write to the master while authenticate will try to read from read replica resulting in not finding the User.

The solution is to set up your routers to use default db for User queries.