【问题标题】:Include a custom field in every Wagtail API response在每个 Wagtail API 响应中包含一个自定义字段
【发布时间】:2019-04-22 20:04:07
【问题描述】:

我的公司正在无头运行 Wagtail,仅使用 API 来为现有 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 的行为?

【问题讨论】:

    标签: wagtail wagtail-apiv2


    【解决方案1】:

    这是我们想出的一种方法。我们的系统中已经存在“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'
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 2017-07-26
      • 2021-08-15
      • 2019-05-08
      • 2015-12-20
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多