maxp
maxp

Reputation: 5554

Some internals of Django auth middleware

In the django.contrib.auth middleware I see the code:

class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), "requires session middleware"
        request.__class__.user = LazyUser()
        return None

Please avdise me why such a form request._ class _.user = LazyUser() used? Why not just request.user = LazyUser() ?

I know what _ class _ attribute means, but as I undersand direct assignment to instance variable will be better. Where I'm wrong?

Upvotes: 4

Views: 747

Answers (2)

Alex Koshelev
Alex Koshelev

Reputation: 17489

LazyUser is descriptor-class. According to documentation it can be only class attribute not instance one:

For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.

Upvotes: 9

SingleNegationElimination
SingleNegationElimination

Reputation: 156278

This is going to affect how requests are created. All such instances will have their user attribute as that particular LazuUser without the need to make that change after each individual request is instantiated.

Upvotes: -1

Related Questions