使用TastyPie与身份验证公开Django模型方法

时间:2018-04-17 00:25:53

标签: django tastypie

我尝试使用TastyPie公开我的Django模型方法并使用BasicAuthentication保护生成的端点,我还需要将使用BasicAuthentication进行身份验证的Django用户传递给我的方法:

class TaskResource(ModelResource):
class Meta:
    queryset = Task.objects.all()
    resource_name = 'jenkins_task'
    excludes = ['id', 'jenkins_job_name']
    authentication = BasicAuthentication()


def prepend_urls(self):
    """ Add the following array of urls to the TaskResource base urls """
    return [
        url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/run%s$" %
            (self._meta.resource_name, trailing_slash()),
            self.wrap_view('run'), name="api_task_run"),
    ]


def run(self, request, **kwargs):
     """ proxy for the Task.call_api method """ 

     # create a basic bundle object for self.get_cached_obj_get.
     basic_bundle = self.build_bundle(request=request)

     print('User: %s' % basic_bundle.request.user)

     # using the primary key defined in the url, obtain the task
     task = self.cached_obj_get(
         bundle=basic_bundle,
         **self.remove_api_resource_names(kwargs))

     # Return what the method output, tastypie will handle the serialization
     return self.create_response(request, task.call_api(basic_bundle.request))

我发送以下POST请求:

Preparing request to http://127.0.0.1:8991/api/jenkins_task/7/run/
Using libcurl/7.54.0 LibreSSL/2.0.20 zlib/1.2.11 nghttp2/1.24.0
Connected to 127.0.0.1 (127.0.0.1) port 8991 (#48)
Server auth using Basic with user 'integration'

POST /api/jenkins_task/7/run/ HTTP/1.1
Host: 127.0.0.1:8991
Authorization: Basic aW50ZWdyYXRpb246aW50ZWdyYXRpb24=
User-Agent: insomnia/5.15.0
Content-Type: application/json
Accept: */*
Content-Length: 67
{
    "snow_number": "INC000000",
    "Store": "0940",
    "Service": "RE"
 }

但是,我得到了代码500,主要是因为 task.call_api 方法中的内部逻辑无法找到 basic_bundle.request.user

所以,我的问题是如果变量请求传递给run()方法,如果它刚刚经过身份验证,那么它不包含Django用户?有什么我想念的吗?

此外,print('User: %s' % basic_bundle.request.user)User: AnonymousUser返回到Django日志

1 个答案:

答案 0 :(得分:1)

视图需要对用户进行身份验证。自定义端点必须执行此操作,如compatibility matrix中所示。查看example of a search endpoint以了解您可能需要在自定义视图中执行的其他操作。

Django用户在Resource.dispatch之后被添加到请求中。