在每个Wagtail API响应中包含一个自定义字段

时间:2019-04-22 20:04:07

标签: wagtail wagtail-apiv2

我的公司仅使用API​​就无头运行Wagtail,以驱动现有Web内部网的各个部分。我们希望在主Web应用程序中每个页面的顶部都包含一个自定义的“编辑栏”,该栏指向Wagtail中匹配记录的“编辑”页面。我们将传递当前用户的请求。然后,我们希望在Wagtail API响应中为所有请求添加一个自定义字段,以表明该用户有权编辑该资源。

为了说明,我正在寻找这样的请求:

http://localhost:32891/api/v2/page/?fields=place_id,location_slug&type=destination.DestinationPage&user_email=foo@bar.com

在这样的响应中,哪些会导致(在完美世界中):

{
    "custom": {
        "can_edit": True,
    },
    "meta": {
        "total_count": 10
    },
    "items": [
        {
            "id": 1,
            "title": "Test blog post",
            "published_date": "2016-08-30",
        },
    ]
}

API表示您可以在页面(或图像和文档)API响应中包括自定义字段,但理想情况下,我希望此对象可通过我们的API用于所有“事物”。这意味着,如果有人请求文档,则无需为每个模型手动返回此字段。

我在考虑是否有可能覆盖BaseAPIEndpoint的行为?

1 个答案:

答案 0 :(得分:0)

这是我们弄清楚该怎么做的一种方法。我们的系统中已经存在“ SecuredPagesAPIEndpoint”页面类。

class SecuredPagesAPIEndpoint(PagesAPIEndpoint):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def listing_view(self, request):
        response = super().listing_view(request)

        # create custom response object
        # this object will contain any number of custom properties that we want to
        # expose to consumers of this API
        response.data['custom'] = {
            'foo': 'BAR'
        }

        return response

这是生成的JSON:

{
    "meta": {
        "total_count": 1
    },
    "items": [
        {
            "id": 8,
            "meta": {
                "type": "destination.DestinationPage",
                "detail_url": "http://localhost/api/v2/page/8/",
                "html_url": "http://localhost/my-page-title/",
                "slug": "my-page-title",
                "first_published_at": "2019-02-19T17:15:13.952708Z"
            },
            "title": "My page title"
        }
    ],
    "custom": {
        "FOO": 'BAR'
    }
}
相关问题