(api_v2_configuration)= # Wagtail API v2 配置指南 ```{warning} v2 API 计划在未来的版本中弃用。见[弃用时间表](api_v2_deprecation),新项目请考虑使用 [v3 API](api_v3)。 ``` 本节的文档将向你展示如何为你的 Wagtail 站点搭建一个公开 API。 尽管该 API 是构建在 Django REST Framework 之上的,但你无需 手动安装它,因为它已经是 Wagtail 的依赖项。 ## 基础配置 ### 启用应用 首先,你需要启用 Wagtail 的 API 应用,让 Django 能看到它。 在你的 Django 项目设置中把 `wagtail.api.v2` 加到 `INSTALLED_APPS`: ```python # settings.py INSTALLED_APPS = [ ... 'wagtail.api.v2', ... ] ``` 你还可以选择把 `rest_framework` 也加到 `INSTALLED_APPS`。 这样在浏览器中查看 API 时它会是可浏览的形式(browsable),但这 对于基础的 JSON 格式输出并非必需。 (api_v2_configure_endpoints)= ### 配置端点 接下来,是时候配置哪些内容将在 API 上暴露了。每种 内容类型(例如页面、图片和文档)都有自己的端点。 端点由路由器组合起来,它提供了你可以挂接到项目其它部分的 url 配置。 Wagtail 提供了多个可用的端点类: - 页面 `wagtail.api.v2.views.PagesAPIViewSet` - 图片 `wagtail.images.api.v2.views.ImagesAPIViewSet` - 文档 `wagtail.documents.api.v2.views.DocumentsAPIViewSet` - 重定向 `wagtail.contrib.redirects.api.RedirectsAPIViewSet`,见 [](redirects_api_endpoint) 你可以继承上述任一端点类来定制其功能。 例如,在下面这种情况下,如果你需要通过设置期望的渲染器类来改变 `APIViewSet`: ```python from rest_framework.renderers import JSONRenderer # ... class CustomPagesAPIViewSet(PagesAPIViewSet): renderer_classes = [JSONRenderer] name = "pages" api_router.register_endpoint("pages", CustomPagesAPIViewSet) ``` 或者更改用于页面结果的目标模型。 ```python from rest_framework.renderers import JSONRenderer # ... class PostPagesAPIViewSet(PagesAPIViewSet): model = models.BlogPage api_router.register_endpoint("posts", PostPagesAPIViewSet) ``` 你可以用 `body_fields`(用于 API 响应顶层的正文字段)和 `meta_fields`(用于响应 `meta` 段内的字段)来控制包含哪些字段。默认情况下,这里添加的字段只会出现在详情视图中。 要让某个字段在该模型被用于嵌套上下文(例如作为关联条目)时也出现,你必须**同时**把它加到 `nested_default_fields` 中。注意该字段必须已经出现在 `body_fields` 或 `meta_fields` 中。 例如,`seo_title` 默认包含在 `meta_fields` 中。要让它出现在嵌套视图中: ```python class CustomFieldsAPIViewSet(PagesAPIViewSet): nested_default_fields = PagesAPIViewSet.nested_default_fields + ["seo_title"] name = "pages" api_router.register_endpoint("pages", CustomFieldsAPIViewSet) ``` 此外,还有一个基础端点类,可用于向 API 添加不同的 内容类型:`wagtail.api.v2.views.BaseAPIViewSet` 在这个示例中,我们将创建一个 API,以默认配置包含全部三种内置内容 类型: ```python # api.py from wagtail.api.v2.views import PagesAPIViewSet from wagtail.api.v2.router import WagtailAPIRouter from wagtail.images.api.v2.views import ImagesAPIViewSet from wagtail.documents.api.v2.views import DocumentsAPIViewSet # Create the router. "wagtailapi" is the URL namespace api_router = WagtailAPIRouter("wagtailapi") # Add the three endpoints using the "register_endpoint" method. # The first parameter is the name of the endpoint (such as pages, images). This # is used in the URL of the endpoint # The second parameter is the endpoint class that handles the requests api_router.register_endpoint("pages", PagesAPIViewSet) api_router.register_endpoint("images", ImagesAPIViewSet) api_router.register_endpoint("documents", DocumentsAPIViewSet) ``` 接下来,注册这些 URL,以便 Django 能把请求路由到 API: ```python # urls.py from .api import api_router urlpatterns = [ ... path('api/v2/', api_router.urls), ... # Ensure that the api_router line appears above the default Wagtail page serving route re_path(r'^', include(wagtail_urls)), ] ``` 使用这套配置,页面可在 `/api/v2/pages/` 访问,图片可在 `/api/v2/images/` 访问,文档可在 `/api/v2/documents/` 访问 (apiv2_page_fields_configuration)= ### 添加自定义页面字段 你很可能需要通过 API 导出一些自定义字段。这可以 通过为每个页面模型在 `api_fields` 属性中添加一份要导出的字段列表 来实现。 例如: ```python # blog/models.py from wagtail.api import APIField class BlogPageAuthor(Orderable): page = models.ForeignKey('blog.BlogPage', on_delete=models.CASCADE, related_name='authors') name = models.CharField(max_length=255) api_fields = [ APIField('name'), ] class BlogPage(Page): published_date = models.DateTimeField() body = RichTextField() feed_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, null=True, ...) private_field = models.CharField(max_length=255) # Export fields over the API api_fields = [ APIField('published_date'), APIField('body'), APIField('feed_image'), APIField('authors'), # This will nest the relevant BlogPageAuthor objects in the API response ] ``` 这样 `published_date`、`body`、`feed_image` 以及一个带 `name` 字段的 `authors` 列表就会在 API 中可用。但要访问这些 字段,你必须通过 [API 本身的参数](apiv2_custom_page_fields)中的 `?type` 来选择 `blog.BlogPage` 类型。 (form_page_fields_api_field)= ### 把表单字段添加到 API 如果你有一个名为 `FormPage` 的 FormBuilder 页面,下面是一个把表单字段暴露到 API 的示例: ```python from wagtail.api import APIField class FormPage(AbstractEmailForm): # ... api_fields = [ APIField("form_fields"), ] ``` ### 自定义序列化器 [序列化器(Serializers)](https://www.django-rest-framework.org/api-guide/fields/)用于把模型的数据库表示转换为 JSON 格式。你可以用 `serializer` 关键字参数重写任何字段的 序列化器: ```python from rest_framework.fields import DateField class BlogPage(Page): ... api_fields = [ # Change the format of the published_date field to "Thursday 06 April 2017" APIField("published_date", serializer=DateField(format="%A %d %B %Y")), ..., ] ``` Django REST Framework 的序列化器都可以接受一个 [source](https://www.django-rest-framework.org/api-guide/fields/#source) 参数,让你 添加字段名不同或根本没有对应模型字段的 API 字段: ```python from rest_framework.fields import DateField class BlogPage(Page): ... api_fields = [ # Date in ISO8601 format (the default) APIField("published_date"), # A separate published_date_display field with a different format APIField( "published_date_display", serializer=DateField(format="%A %d %B %Y", source="published_date"), ), ..., ] ``` 这样会给 API 添加两个字段(为简洁起见省略了其它字段): ```json { "published_date": "2017-04-06", "published_date_display": "Thursday 06 April 2017" } ``` (apiv2_streamfield_configuration)= ### API 中的 StreamField 区块 当 StreamField 区块的值被序列化供 API 使用时,Wagtail 默认采用与数据库相同的表示。例如,这个模型: ```python # blog/models.py from wagtail.models import Page from wagtail.fields import StreamField from wagtail.blocks import CharBlock, ImageChooserBlock class BlogPage(Page): body = StreamField( [ ("heading", CharBlock()), ("photo", ImageChooserBlock()), ] ) ``` 默认会产生这样的 API 输出: ```json { "body": [ {"type": "heading", "value": "Hello world", "id": "abc123"}, {"type": "photo", "value": 42, "id": "def456"} ] } ``` `CharBlock` 产生字符串值,而 `ImageChooserBlock` 的引用对应图片的主键。 #### 用于自定义区块序列化的 `get_api_representation` 要返回更丰富的数据,你可以在 `StructBlock` 中定义 `get_api_representation`。下面是另一个示例,它直接内联返回完整的图片数据,而不只是 ID: ```python # blog/blocks.py from wagtail.images.blocks import ImageChooserBlock class APIImageChooserBlock(ImageChooserBlock): def get_api_representation(self, value, context=None): # value is the fully-loaded Image object, not just the integer ID return { "id": value.id, "title": value.title, } ``` 这样 API 会直接内联返回完整的图片数据,无需第二次请求。这种做法对基于 StructBlock 的所有区块都有效,无论它们位于区块层级中的哪个位置。 (api_v2_rich_text)= ### API 中的富文本 默认情况下,`RichTextField` 的值以 Wagtail 的数据库 HTML 格式序列化,详见 [](rich_text_internals)。当 API 客户端会直接操作富文本中引用外部数据的标识符(例如按 ID 获取更多关于页面链接或图片的数据)时,这很有用。 如果改为返回可直接用于展示的 HTML(等价于 `|richtext` 模板过滤器),请使用 `?rich_text_format=html` 查询参数,或在设置中用 `WAGTAILAPI_RICH_TEXT_FORMAT = 'html'` 设定项目级默认值。默认格式是 `db_html`。 如果希望对每个字段单独控制、不受查询参数影响,你仍可以使用一个行为类似 `|richtext` 模板过滤器的自定义序列化器: ```python from rest_framework.fields import CharField from wagtail.rich_text import expand_db_html class RichTextSerializer(CharField): def to_representation(self, instance): representation = super().to_representation(instance) return expand_db_html(representation) ``` 然后我们可以修改 `api_fields` 的定义,让 `body` 使用这个新的序列化器: ```python (APIField("body", serializer=RichTextSerializer()),) ``` (api_v2_images)= ### API 中的图片 `ImageRenditionField` 序列化器 让你可以把图片的 rendition 加到 API 中。它需要一个图像 过滤器字符串,指定要对图片执行的缩放操作。它也可以 接受上文所述的 `source` 关键字参数。 例如: ```python from wagtail.api import APIField from wagtail.images.api.fields import ImageRenditionField class BlogPage(Page): ... api_fields = [ # Adds information about the source image (eg, title) into the API APIField("feed_image"), # Adds a URL to a rendered thumbnail of the image to the API APIField( "feed_image_thumbnail", serializer=ImageRenditionField("fill-100x100", source="feed_image"), ), ..., ] ``` 这会在 JSON 中添加以下内容: ```json { "feed_image": { "id": 45529, "meta": { "type": "wagtailimages.Image", "detail_url": "https://www.example.com/api/v2/images/12/", "download_url": "/media/images/a_test_image.jpg", "tags": [] }, "title": "A test image", "width": 2000, "height": 1125 }, "feed_image_thumbnail": { "url": "/media/images/a_test_image.fill-100x100.jpg", "full_url": "https://www.example.com/media/images/a_test_image.fill-100x100.jpg", "width": 100, "height": 100, "alt": "image alt text" } } ``` 注意:`download_url` 是原始上传文件的路径,而 `feed_image_thumbnail['url']` 是渲染后图片的 url。 当你使用其它存储后端(例如 S3)时,如果你的媒体文件配置得当, `download_url` 会返回指向该图片的 URL。 对于源图片集合可能包含 SVG 的情况,`ImageRenditionField` 构造函数接受一个 `preserve_svg` 参数。当 `preserve_svg` 为 `True` 时,`ImageRenditionField` 的行为如 `image` 模板标签的 `preserve-svg` 参数所述(见 [](svg_images) 的文档)。 #### 过滤器规格 `ImageRenditionField` 中的 `filter_spec` 参数决定图片将如何被缩放和处理。完整的可用操作及其语法列表,见[过滤器规格文档](../../../topics/images)。 常见示例如下: ```python # Square crop and fill APIField("thumbnail", serializer=ImageRenditionField("fill-300x300", source="image")) # Maintain aspect ratio with maximum dimensions APIField("preview", serializer=ImageRenditionField("max-800x600", source="image")) # Exact dimensions without cropping APIField("banner", serializer=ImageRenditionField("width-1200", source="image")) # Chained operations (multiple filters combined) APIField( "compressed_thumb", serializer=ImageRenditionField("fill-200x200|jpegquality-60", source="image"), ) ``` 生成的 rendition URL 会包含在 API 响应中,让客户端可以直接访问优化后的图片版本,而无需额外处理。 ### 认证 要保护对 API 的访问,你可以实现 Django REST Framework 提供的某种[认证](https://www.django-rest-framework.org/api-guide/authentication/)方式,例如 [Token 认证](https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication): ```python # api.py from rest_framework.permissions import IsAuthenticated # ... class CustomPagesAPIViewSet(PagesAPIViewSet): name = "pages" permission_classes = (IsAuthenticated,) api_router.register_endpoint("pages", CustomPagesAPIViewSet) ``` 并扩展设置中的 ```python # settings.py INSTALLED_APPS = [ ... 'rest_framework.authtoken', ... ] ... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication" ], } ``` 别忘了运行该应用的迁移。 你的 API 端点将只能通过携带所生成 `Token exampleSecretToken123xyz` 的 Authorization 头访问。 令牌可以在 Django 管理后台的 Auth Token 下生成,也可以使用 `manage.py` 命令 `drf_create_token` 生成。 注意:如果你在生产环境中使用 `TokenAuthentication`,必须确保你的 API 只能通过 `https` 访问。 ## 其它设置 ### `WAGTAILAPI_BASE_URL` (使用前端缓存失效时必须设置) 它用于两处:生成指向文档文件的绝对 URL,以及 使缓存失效。 如果没有设置,生成文档 URL 时会回退到当前请求的主机名。 但缓存失效无法这样做,因此在把该模块与 `wagtailfrontendcache` 模块一起使用时, 必须设置该项。 ### `WAGTAILAPI_SEARCH_ENABLED` (默认:True) 把它设为 false 会禁用全文搜索。这对所有 端点都生效。 ### `WAGTAILAPI_LIMIT_MAX` (默认:20) 它让你可以更改用户一次最多可请求的结果数量 。这对所有端点都生效。设为 `None` 表示不限制。 可与 [`?limit` 和 `?offset` 查询参数](apiv2_pagination)配合,取出想要的结果数量。