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

Exposing Django model method using TastyPie with Authentication

我正在尝试使用 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.

所以,我的问题是,如果刚刚通过身份验证,传递给 运行() 方法的变量 request 为何不包含 Django 用户?有什么我想念的吗?

此外,print('User: %s' % basic_bundle.request.user) return User: AnonymousUser 进入 Django 日志

视图需要对用户进行身份验证。自定义端点必须执行此操作,如 example of a search endpoint. Check out Resource.dispatch 中所示,您可能需要在自定义视图中执行其他操作。

Django用户在successful authentication之后添加到请求中。