【问题标题】:Model resource with users as FK TastyPie API以用户为 FK TastyPie API 的模型资源
【发布时间】:2013-11-01 15:22:36
【问题描述】:

使用 TastyPie 我有一个模型资源,它有一个 FK 用户。当我对 API 进行 POST 时,我必须像这样包含用户 ID:

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

我的用户必须通过登录或使用 API 密钥以及用户名和密码进行身份验证。在这两种情况下我已经知道用户是谁

1) 如何让用户确保 user1 不会为 user2 创建资源?

2) 或者发送用户 ID 是违反直觉的?我是否应该以某种方式从授权详细信息中获取用户,如果可以,如何?

【问题讨论】:

    标签: python django django-models tastypie


    【解决方案1】:

    回答问题 #1:Tastypie 文档描述了how to create per-user resources。假设用户已经是请求的一部分:

    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)
    

    要回答问题 #2,您可能应该让用户参与会话。

    【讨论】:

    • obj_create() 中 super() 的第一个参数不应该是 'MyResource' 吗?
    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    相关资源
    最近更新 更多