简体   繁体   English

使用用户作为FK TastyPie API的模型资源

[英]Model resource with users as FK TastyPie API

Using TastyPie I have a model resource which has a FK user. 使用TastyPie我有一个拥有FK用户的模型资源。 When I make a POST to the API I have to include the user id like this: 当我对API发布POST时,我必须包含这样的用户ID:

 data : JSON.stringify({ name : 'value a', user : '12' }), 

My users have to authenticate either by logging in or using an API Key and username and password. 我的用户必须通过登录或使用API​​密钥以及用户名和密码进行身份验证。 In both cases I already know who the user is . 在这两种情况下, 我都知道用户是谁

1) How can I make user sure that user1 does not create a resource for user2 ? 1)如何让用户确保user1不为user2创建资源?

2) or it is counterintuitive to send the user ID at all? 2)或者完全发送用户ID是违反直觉的? Should I somehow get the user from the authorization details, if so how? 我应该以某种方式从授权细节中获取用户,如果是这样的话?

To answer question #1: The Tastypie documentation describes how to create per-user resources . 回答问题#1:Tastypie文档描述了如何创建每用户资源 Assuming that the user is already part of the request: 假设用户已经是请求的一部分:

class MyResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'environment'
        list_allowed_methods = ['get', 'post']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

    # Only allow creation of objects belonging to the user
    def obj_create(self, bundle, **kwargs):
        return super(EnvironmentResource, self).obj_create(bundle, user=bundle.request.user)

    # Only allow accessing resources for this user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

To answer question #2, you should probably have the user be part of the session. 要回答问题#2,您应该让用户成为会话的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM