简体   繁体   English

从 Django 模型的保存方法按需重新验证 Next.js 站点

[英]Revalidate on-demand a Next.js site from Django model's save method

I have a next.js site deployed to Vercel, that fetches data from an API provided by Django. Next.js has this new feature (Incremental Static Regeneration On-Demand) where you can rebuild a specific page without need to rebuild the entire site with an url like this:我有一个部署到 Vercel 的 next.js 站点,它从 Django 提供的 API 获取数据。Next.js 具有此新功能(增量 Static 按需重新生成),您可以在其中重建特定页面,而无需使用这个:

https://<my-site.com>/api/revalidate?secret=my-token https://<my-site.com>/api/revalidate?secret=my-token

I need the next.js site rebuild some pages when the database changes, so it shows the new data, and i tried to make a request (with requests package) in the save method like this:我需要 next.js 站点在数据库更改时重建一些页面,因此它显示新数据,并且我尝试在保存方法中发出请求(带有请求包),如下所示:

def save(self, *args, **kwargs):
    super(MyModel, self).save(*args, **kwargs)
    r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>")

It seems to work when i trigger that url from my browser, but it doesn't work when i trigger it from Django. The response of this Response object (r) is a 200 Status Code, as expected, with {"revalidated":true} (r.text), but it doesn't update the site anyways.当我从我的浏览器触发 url 时它似乎工作,但当我从 Django 触发它时它不起作用。这个响应 object (r) 的响应是一个 200 状态代码,正如预期的那样,带有 {"revalidated": true} (r.text),但它不会更新站点。

How can i implement this?我该如何实施?

EDIT: here's the pages/api/revalidate.js code:编辑:这是 pages/api/revalidate.js 代码:

export default async function handler(req, res) {  
    if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
        return res.status(401).json({ message: 'Invalid token' })
    }
    try {
        await res.unstable_revalidate('/')
        await res.unstable_revalidate('/url')
        return res.json({ revalidated: true })
    } catch (err) {
        return res.status(500).send('Error revalidating')
    }
}

Had similar problem.有类似的问题。 I think it wasn't working because you actually need to save before revalidation.我认为它不起作用,因为您实际上需要在重新验证之前保存。

This worked for me:这对我有用:

def save(self, *args, **kwargs):
    try:
        return super().save(*args, **kwargs)
    finally:
        r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM