如何在 Piston 类方法中访问 request.user
我有一个模型,其中包含一个 ManyToMany to User 来跟踪哪些用户“最喜欢”特定的模型实例。
在此模型的 API 中,当经过身份验证的用户请求时,我想包含一个“is_favorite”布尔值。然而,似乎任何不是直接模型属性的 api 字段都必须实现为类方法,在 Piston 中调用时不会获得对请求对象的引用,因此我无法知道当前用户是谁是。
来自 Piston 文档:
除了这些之外,您还可以定义您想要的任何其他方法。您可以通过在 fields 指令中包含它们的名称来使用它们,这样,将使用单个参数调用该函数:模型的实例。然后它可以返回任何内容,并且返回value 将用作该键的值。
那么,如果只有 Piston CRUD 方法获取请求的实例,我的类方法字段如何生成与当前经过身份验证的用户相关的输出?
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 requested by an authenticated user, I'd like to include an 'is_favorite' boolean. However, it seems that any api fields that aren't straight model attributes must be implemented as a class method, which when called in Piston does not get a reference to the request object, and therefore I have no way to know who the current user is.
From the Piston docs:
In addition to these, you may define any other methods you want. You can use these by including their names in the fields directive, and by doing so, the function will be called with a single argument: The instance of the model. It can then return anything, and the return value will be used as the value for that key.
So, if only the Piston CRUD methods get an instance of the request, how can my classmethod fields generate output which is relevant to the current authenticated user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道活塞 API,但是如何使用线程本地中间件来访问请求,
将其添加到中间件
更新设置
并使用 ThreadLocals 中间件以及您想要访问请求的任何位置 中间件修改中间件以仅在线程局部变量中设置
request.user
import get_request
如果您只想获取当前用户,请从I am not aware of the piston API, but how about using the thread locals middleware to access the request
add this to middleware
and update the settings with the ThreadLocals middleware
and wherever you want to access the request
import get_request
from middlewareif you want to just get the current user, modify the middleware to set only
request.user
in thread locals从活塞wiki页面它说你可以指定外键的内容和通过嵌套属性实现多对多字段。在你的情况下
编辑:另一种稍微有点老套的方法(如果你不希望朋友在 is_friended 为 false 时根本不通过)将是手动创建一个 dict 对象,该对象的结构如何喜欢,然后退货。活塞处理 dict a 与内置发射器一起工作(当然是 JSON 的,还没有尝试过其他的)
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
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)