Django 和服务 worker - 在应用程序的根 url 处提供 "sw.js"

标签 django django-urls django-staticfiles service-worker

因此,我正在使用 Service Worker 构建具有离线支持的 Django 渐进式 Web 应用程序。

根据 google's documentation ,sw.js 文件应该位于应用程序 url 的根目录:

You need to do this because the scope of a service worker (the set of urls that the ServiceWorker will load for) is defined by the directory where it resides.



目前,我正在为来自 http://example.com/static/ 的所有静态 Assets 提供服务。文件夹。但我需要在如下网址提供此特定文件:http://example.com/sw.js .

知道我如何实现这一目标吗?我可以制定特定的 nginx 规则来执行此重定向,但我不知道这是否是最干净的方法。也许这个设置应该驻留在 urls.py 中?

备注 : 我见过this question建议使用 django.conf.urls.static 中的 static() 方法.但是django's docs说静态方法仅供开发使用,所以对我不利。

注(2) : 我想我可以改变 STATIC_URL设置,但我对从/static 目录提供的文件感到满意。我只希望这个文件位于 url 的根目录下。

最佳答案

您可以将 javascript 用作 View ,而不仅仅是 html。把它放在你的项目 urls.py 中

url(r'^service-worker.js', cache_control(max_age=2592000)(TemplateView.as_view(
    template_name="service-worker.js",
    content_type='application/javascript',
)), name='service-worker.js'),

然后把你的 service-worker.js在您的模板目录中。

好处是您现在还可以在 javascript 文件中使用模板标签,如静态。

关于Django 和服务 worker - 在应用程序的根 url 处提供 "sw.js",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696595/

相关文章:

Django:表单保存覆盖

python - Django 静态文件未在 Azure 上提供

django - 为什么 DEBUG=False 设置会使我的 django 静态文件访问失败?

python - Django 是否以某种方式缓存 url 正则表达式模式?

python - DJango - NoReverseMatch 错误

python - 值错误 : Missing staticfiles manifest entry for 'favicon.ico'

django - `.create()` 方法默认不支持可写的点源字段。为序列化器编写显式的 `.create()` 方法

python - 使用 django-rest-interface

python - MEDIA_URL 元组

regex - 使用 "OR"条件的正则表达式