How to access the request.user in a Piston classmethod

前端 未结 2 382
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 03:11

I have a model which contains a ManyToMany to User to keep track of which users have \'favorited\' a particular model instance.

In my API for this model, when reques

2条回答
  •  醉酒成梦
    2021-01-14 04:13

    I am not aware of the piston API, but how about using the thread locals middleware to access the request

    add this to middleware

    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
    

    and update the settings with the ThreadLocals middleware

    and wherever you want to access the request import get_request from middleware

    if you want to just get the current user, modify the middleware to set only request.user in thread locals

提交回复
热议问题