每次我打开根站点目录时,Serviceworker.js代码都会显示在页面上(仅在谷歌中),并在ctrl+f5之后被替换



我想,这是关于django-pwa的。这个问题只出现在googlechrome中(在本地模式下,它甚至可以在127.0.0.1:8000上正常工作,但在localhost:8000上不工作(。

我的项目结构:

D:.
├───api
│   └───migrations
├───core
│   └───__pycache__
├───games
│   └───migrations
├───main
│   ├───migrations
│   └───__pycache__
├───static
│   ├───images
│   └───js
├───staticfiles
└───templates

看起来,chrome浏览器首先请求pwa.urls的空路径,但其他浏览器请求主url。我真的不知道如何让chrome从主应用程序请求我的url。

这是我的urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from rest_framework.schemas import get_schema_view
import debug_toolbar
schema_url_patterns = [
path('api/v1/', include('api.urls')),
]
urlpatterns = [
path(r'', include('main.urls')),
path('openapi', get_schema_view(
title="Gamers Gazette",
description="API!",
version="1.0.0",
patterns=schema_url_patterns,
), name='openapi-schema'),
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url':'openapi-schema'}
), name='swagger-ui'),
path('redoc/', TemplateView.as_view(
template_name='redoc.html',
extra_context={'schema_url':'openapi-schema'}
), name='redoc'),
path('admin/', admin.site.urls),
path('games/', include('games.urls')),
path('api/v1/', include('api.urls')),
path("", include("pwa.urls")),
] 
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path('__debug__/', include('debug_toolbar.urls')),
] + urlpatterns

这是我的serviceworker.js:

var staticCacheName = 'djangopwa-v1';

self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
)
});
// Clear cache on activate
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName => (cacheName.startsWith("django-pwa-")))
.filter(cacheName => (cacheName !== staticCacheName))
.map(cacheName => caches.delete(cacheName))
);
})
);
});
// Serve from Cache
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
.catch(() => {
return caches.match('offline');
})
)
});

设置.py:

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/js', 'serviceworker.js')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-fl61624yl*s1hbc9lt@9ipbmyytdrurqo@dc%$3pdz9g8haof3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SESSIONS_ENGINE='django.contrib.sessions.backends.cache'
ALLOWED_HOSTS = []
INSTALLED_APPS = [
#apps
'main',
'api',
'games',
#django staff
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#drf staff
'rest_framework',
#debugging
"debug_toolbar",
#third_party
"pwa"
]
MIDDLEWARE = [
#django staff
"debug_toolbar.middleware.DebugToolbarMiddleware",
'debug_toolbar_force.middleware.ForceDebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'main_db',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': '5432' 
}
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
if DEBUG:
import socket  # only if you haven't already imported this
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2']
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static/"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': 'cache:11211',
}
}
#PWA STAFF
PWA_APP_NAME = 'test app'
PWA_APP_DESCRIPTION = "test app PWA"
PWA_APP_THEME_COLOR = '#000000'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_STATUS_BAR_COLOR = 'default'
PWA_APP_ICONS = [
{
'src': 'static/images/icon.png',
'sizes': '160x160'
}
]
PWA_APP_ICONS_APPLE = [
{
'src': 'static/images/icon.png',
'sizes': '160x160'
}
]
PWA_APP_SPLASH_SCREEN = [
{
'src': 'static/images/icon.png',
'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
}
]
PWA_APP_DIR = 'ltr'
PWA_APP_LANG = 'ru-RU'
import django_heroku
django_heroku.settings(locals())

询问:你需要

很抱歉迭代,问题在谷歌。它缓存了一个错误版本的脚本,清理缓存后一切正常。

最新更新