wagtail - 在每个 Wagtail API 响应中包含一个自定义字段
问题描述
我的公司正在无头运行 Wagtail,仅使用 API 来为现有 Web 内部网的部分提供动力。我们希望在主 Web 应用程序的每个页面顶部包含一个自定义的“编辑栏”,它指向 Wagtail 中匹配记录的“编辑”页面。我们将与请求一起传递当前用户。然后我们想在 Wagtail API 响应中包含一个自定义字段,用于指示用户编辑该资源的权限的所有请求。
为了说明,我希望提出这样的请求:
这将导致(在一个完美的世界中)这样的响应:
{
"custom": {
"can_edit": True,
},
"meta": {
"total_count": 10
},
"items": [
{
"id": 1,
"title": "Test blog post",
"published_date": "2016-08-30",
},
]
}
API 表明您可以在页面(或图像和文档)、API 响应中包含自定义字段,但理想情况下,我希望此对象可通过我们的 API 用于所有“事物”。这意味着如果有人请求文档,我不必为每个单独的模型手动返回此字段。
我认为有可能覆盖BaseAPIEndpoint
?
解决方案
这是我们想出如何做到这一点的一种方法。我们的系统中已经存在“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'
}
}
推荐阅读
- amazon-web-services - 如何在亚马逊 ec2 服务器上部署 codeigniter 应用程序?
- jpql - jpql 语句语法错误,不是有效的条件表达式
- google-apps-script - if 条件下相同的值不匹配
- algorithm - 为什么 Floyd Warshall 算法只需要 O(n^2) 空间?
- linux - 通过各种平台高效使用 LLVM
- node.js - 部署到 Google 应用引擎时获取请求有效但不发布请求?
- db2 - Teradata 聚簇表的 DB2 等效性
- wordpress - 如何在没有参数的情况下重定向到新域
- flutter - Flutter Get Request with Bearer Token (JWT) - Django 后端
- logistic-regression - SPSS回归中无法收敛是什么意思?