Python 如何在方法中访问request.user
我有一个模型,其中包含了许多对用户的信息,以跟踪哪些用户“喜欢”某个特定的模型实例 在这个模型的API中,当经过身份验证的用户请求时,我希望包含一个“is_favorite”布尔值。然而,似乎任何不是直接模型属性的api字段都必须作为类方法实现,在活塞中调用时,该类方法不会获得对请求对象的引用,因此我无法知道当前用户是谁 从活塞文档: 除此之外,您还可以定义所需的任何其他方法。您可以通过在fields指令中包含它们的名称来使用它们,这样,函数将通过一个参数调用:模型的实例。然后它可以返回任何内容,返回值将用作该键的值Python 如何在方法中访问request.user,python,django,django-piston,Python,Django,Django Piston,我有一个模型,其中包含了许多对用户的信息,以跟踪哪些用户“喜欢”某个特定的模型实例 在这个模型的API中,当经过身份验证的用户请求时,我希望包含一个“is_favorite”布尔值。然而,似乎任何不是直接模型属性的api字段都必须作为类方法实现,在活塞中调用时,该类方法不会获得对请求对象的引用,因此我无法知道当前用户是谁 从活塞文档: 除此之外,您还可以定义所需的任何其他方法。您可以通过在fields指令中包含它们的名称来使用它们,这样,函数将通过一个参数调用:模型的实例。然后它可以返回任何内容
因此,如果只有活塞CRUD方法获得请求的实例,我的classmethod字段如何生成与当前经过身份验证的用户相关的输出?我不知道活塞API,但如何使用线程局部变量中间件访问请求 将此添加到中间件
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中间件更新设置
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
无论您想从何处访问请求import get\u请求
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
如果您只想获取当前用户,请修改中间件以仅设置请求。用户
在线程局部变量中从活塞中,它表示您可以通过嵌套属性指定外键和多对多字段的内容。就你而言
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
编辑:另一种稍微有点老套的方法是手动创建一个按您喜欢的方式构造的dict对象,然后返回该对象(如果“is\u friended”为false,您根本不想让朋友通过)。活塞处理dict a与内置发射器一起工作(JSON发射器是肯定的,没有尝试其他发射器)很好地解决了活塞API中的缺陷。我认为真正的“正确”答案应该是完全不同的,但这确实奏效了,谢谢!