How to access the request.user in a Piston classmethod

南楼画角 提交于 2019-12-01 08:53:52

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

From the piston wiki page it says that you may specify the contents of foreign keys and many to many fields by nesting attributes. In your case

class FriendHandler(BaseHandler):
    allowed_methods = ('GET',)
    model = User
    fields = ('userfield_1', 'userfield_2', ('friends', ('is_friended')))

    def read(self, request):
        # Anything else you might want to do, but return an object of type User
        # Or whatever your model happens to be called

EDIT: Another slightly hacky way to do it (if you don't want the friend to get passed at all if the is_friended is false) would be to manually create a dict object structured how you like, and then return it. piston processes the dict a works with the built in emitters (the JSON one for sure, haven't tried the others)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!