How to access request.user in a Piston class method

I have a model that contains ManyToMany for the user to track which users "prefer" a particular instance of the model.

In my API for this model, when an authenticated user asked me, I would like to add the boolean value 'is_favorite'. However, it seems that any api fields that are not direct attributes of the model should be implemented as a class method that, when called in Piston, does not receive a link to the request object, and therefore I have no way to find out who the current user is.

From the Piston docs:

In addition to these, you can define any other methods that you want. You can use them by including their names in the fields directive, and thus the function will be called with one argument: an instance of the model. . It can then return something, and the return value will be used as the value for this key.

So, if only the Piston CRUD methods get an instance of the request, how can my class class fields generate output that is relevant to the currently authenticated user?

+3
source share
2 answers

I am not aware of the piston API, but what about using middleware flow locators to access the request

try:                                                                    
    from threading import local                                         
except ImportError:                                                     
    from django.utils._threading_local import local                     

_thread_locals = local()                                                
def get_request():                                                
    return getattr(_thread_locals, 'request', None)                       

class ThreadLocals(object):                                             
    def process_request(self, request):                                 
        _thread_locals.request = request

ThreadLocals

, import get_request

, , request.user

0

0

Source: https://habr.com/ru/post/1761838/


All Articles