创建自定义 Wagtail OEmbedFinder

Creating a custom Wagtail OEmbedFinder

我正在关注 the documentation and also this example 在我的 Wagtail 站点中创建自定义 OEmbed Finder。 (最终我想修改 YouTube 视频的 HTML 输出以使用 youtube-nocookie.com 域,而不是 youtube.com。)

我在 myapp.embeds.finders.oembed.py 中创建了这个:

from wagtail.embeds.finders.oembed import OEmbedFinder

class YouTubeOEmbedFinder(OEmbedFinder):

    def find_embed(self, url, max_width=None):
        embed = super().find_embed(url, max_width)

        # Just to see that it's doing something:
        embed['html'] = '<p>Hello</p>'

        return embed

并在我的设置中添加了这个:

from wagtail.embeds.oembed_providers import youtube

WAGTAILEMBEDS_FINDERS = [
    {
        'class': 'myapp.embeds.finders.oembed.YouTubeOEmbedFinder',
        'providers': [youtube],
    },
    {
        # Handles all other oEmbed providers the default way
        'class': 'wagtail.embeds.finders.oembed',
    },
]

但没有什么不同 - 标准的 YouTube 嵌入在已发布的页面中。据我所知,我的 find_embed() 方法从未被调用过。我一定是犯了一些愚蠢的错误,但我很难过。

调试变得更加困难,因为我没有意识到一件事:嵌入,包括它们的 HTML,并不总是在您重新保存或发布页面时重新生成它们用在。它们只有在 URL 发生变化时才会重新生成。这就是我的 find_embed() 方法从未被调用的原因;因为我只是重新发布页面,没有更改嵌入中使用的 URL。

一旦意识到这一点,我尝试做的事情的解决方案就很简单了。

在我的 settings.py:

from wagtail.embeds.oembed_providers import youtube

WAGTAILEMBEDS_FINDERS = [
    {
        'class': 'myapp.embeds.finders.oembed.YouTubeOEmbedFinder',
        'providers': [youtube],
    },
    {
        # Handles all other oEmbed providers the default way
        'class': 'wagtail.embeds.finders.oembed',
    },
]

然后在myapp/embeds/finders/oembed.py:

from wagtail.embeds.finders.oembed import OEmbedFinder

class YouTubeOEmbedFinder(OEmbedFinder):
    """
    Ensures that all YouTube embeds use the youtube-nocookie.com domain
    instead of youtube.com.
    """

    def find_embed(self, url, max_width=None):
        embed = super().find_embed(url, max_width)

        embed['html'] = embed['html'].replace(
                                        'youtube.com/embed',
                                        'youtube-nocookie.com/embed')
        return embed

那只是 更改我所有现有 YouTube 嵌入的 URL 的情况(例如,将 ?v=2 添加到他们的末尾URLs) 并重新发布页面。