如何防止 Django 将管理 URI 覆盖为 /admin 而不是 /api/admin/
How to prevent Django from overriding admin URI to /admin instead of /api/admin/
正在努力将 Django API 放入 Kubernetes。
发送到 /
的任何流量,ingress-nginx
控制器发送到 React FE。任何发送到 /api
的流量都会发送到 Django BE。
这是ingress-serivce.yaml
的相关部分:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /?(.*)
backend:
serviceName: client-cluster-ip-service
servicePort: 3000
- path: /api/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
这是url.py
:
来自 django.contrib 导入管理员
来自 django.urls 导入包含,路径
urlpatterns = [
path('auth/', include('authentication.urls'), name='auth'),
path('admin/', admin.site.urls, name='admin'),
]
client
部分工作得很好。 minikube
IP 是 192.168.99.105
。导航到该 IP 会加载反应前端。
导航到 192.168.99.105/api/auth/test/
将我带到一个 `"Hello World!" 响应,我很快就把它们放在一起了。
然而,当我试图去192.168.99.105/api/admin
。它会自动将我重定向到 /admin/login/?next=/admin/
,鉴于 /api
正在被删除,它不存在。 有什么办法可以防止这种行为吗?
我也刚试过这个:
入口-service.yaml
- http:
paths:
- path: /?(.*)
backend:
serviceName: client-cluster-ip-service
servicePort: 3000
- path: /api/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
- path: /admin/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
urls.py
urlpatterns = [
path('auth/', include('authentication.urls'), name='auth'),
path('/', admin.site.urls),
]
这只会产生 "Not Found"。
我也尝试使用 the documentation 中显示的这种模式作为前缀:
urlpatterns = [
path('api/', include([
path('auth/', include('authentication.urls'), name='auth'),
path('admin/', admin.site.urls),
])),
]
但这只是 /api/api
。
这是在 site-packages/django/contrib/admin/sites
中为 admin/
定义的路由:
# Admin-site-wide views.
urlpatterns = [
path('', wrap(self.index), name='index'),
path('login/', self.login, name='login'),
path('logout/', wrap(self.logout), name='logout'),
path('password_change/', wrap(self.password_change, cacheable=True), name='password_change'),
path(
'password_change/done/',
wrap(self.password_change_done, cacheable=True),
name='password_change_done',
),
path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
path(
'r/<int:content_type_id>/<path:object_id>/',
wrap(contenttype_views.shortcut),
name='view_on_site',
),
]
我猜 ''
是导致 Django 从 URL 中剥离 /api
并使其成为 192.168.99.105/admin
而不是 192.168.99.105/api/admin
的原因。
好吧,终于想通了。绝对是 Django 设置。将以下内容添加到 Django settings.py
:
FORCE_SCRIPT_NAME = '/api/'
然后我不得不更新 STATIC_URL
因为它不再为管理门户提供资产:
STATIC_URL = '/api/static/`
我正在使用的完整 settings.py
,但实际上唯一需要更改的是添加 FORCE_SCRIPT_NAME
和更新 STATIC_URL
:
Django settings for config project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from datetime import timedelta
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Forces Django to not strip '/api' from the URI
FORCE_SCRIPT_NAME = '/api/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ['DEBUG'] == 'True'
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'192.168.64.7'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party packages
'rest_framework',
# Local packages
'authentication'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['PGDATABASE'],
'USER': os.environ['PGUSER'],
'PASSWORD': os.environ['PGPASSWORD'],
'HOST': os.environ['PGHOST'],
'PORT': 1423
}
}
# REST Framework settings
# https://www.django-rest-framework.org/
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
}
# SIMPLE_JWT Settings
# https://github.com/davesque/django-rest-framework-simplejwt
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': os.environ['SECRET_KEY'],
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/api/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Dockerfile
FROM python:3.7-slim
ENV PYTHONUNBUFFERED 1
WORKDIR /app
EXPOSE 5000
COPY requirements*.txt ./
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]
正在努力将 Django API 放入 Kubernetes。
发送到 /
的任何流量,ingress-nginx
控制器发送到 React FE。任何发送到 /api
的流量都会发送到 Django BE。
这是ingress-serivce.yaml
的相关部分:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /?(.*)
backend:
serviceName: client-cluster-ip-service
servicePort: 3000
- path: /api/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
这是url.py
:
来自 django.contrib 导入管理员 来自 django.urls 导入包含,路径
urlpatterns = [
path('auth/', include('authentication.urls'), name='auth'),
path('admin/', admin.site.urls, name='admin'),
]
client
部分工作得很好。 minikube
IP 是 192.168.99.105
。导航到该 IP 会加载反应前端。
导航到 192.168.99.105/api/auth/test/
将我带到一个 `"Hello World!" 响应,我很快就把它们放在一起了。
然而,当我试图去192.168.99.105/api/admin
。它会自动将我重定向到 /admin/login/?next=/admin/
,鉴于 /api
正在被删除,它不存在。 有什么办法可以防止这种行为吗?
我也刚试过这个:
入口-service.yaml
- http:
paths:
- path: /?(.*)
backend:
serviceName: client-cluster-ip-service
servicePort: 3000
- path: /api/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
- path: /admin/?(.*)
backend:
serviceName: server-cluster-ip-service
servicePort: 5000
urls.py
urlpatterns = [
path('auth/', include('authentication.urls'), name='auth'),
path('/', admin.site.urls),
]
这只会产生 "Not Found"。
我也尝试使用 the documentation 中显示的这种模式作为前缀:
urlpatterns = [
path('api/', include([
path('auth/', include('authentication.urls'), name='auth'),
path('admin/', admin.site.urls),
])),
]
但这只是 /api/api
。
这是在 site-packages/django/contrib/admin/sites
中为 admin/
定义的路由:
# Admin-site-wide views.
urlpatterns = [
path('', wrap(self.index), name='index'),
path('login/', self.login, name='login'),
path('logout/', wrap(self.logout), name='logout'),
path('password_change/', wrap(self.password_change, cacheable=True), name='password_change'),
path(
'password_change/done/',
wrap(self.password_change_done, cacheable=True),
name='password_change_done',
),
path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
path(
'r/<int:content_type_id>/<path:object_id>/',
wrap(contenttype_views.shortcut),
name='view_on_site',
),
]
我猜 ''
是导致 Django 从 URL 中剥离 /api
并使其成为 192.168.99.105/admin
而不是 192.168.99.105/api/admin
的原因。
好吧,终于想通了。绝对是 Django 设置。将以下内容添加到 Django settings.py
:
FORCE_SCRIPT_NAME = '/api/'
然后我不得不更新 STATIC_URL
因为它不再为管理门户提供资产:
STATIC_URL = '/api/static/`
我正在使用的完整 settings.py
,但实际上唯一需要更改的是添加 FORCE_SCRIPT_NAME
和更新 STATIC_URL
:
Django settings for config project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from datetime import timedelta
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Forces Django to not strip '/api' from the URI
FORCE_SCRIPT_NAME = '/api/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ['DEBUG'] == 'True'
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'192.168.64.7'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party packages
'rest_framework',
# Local packages
'authentication'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['PGDATABASE'],
'USER': os.environ['PGUSER'],
'PASSWORD': os.environ['PGPASSWORD'],
'HOST': os.environ['PGHOST'],
'PORT': 1423
}
}
# REST Framework settings
# https://www.django-rest-framework.org/
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
}
# SIMPLE_JWT Settings
# https://github.com/davesque/django-rest-framework-simplejwt
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': os.environ['SECRET_KEY'],
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/api/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Dockerfile
FROM python:3.7-slim
ENV PYTHONUNBUFFERED 1
WORKDIR /app
EXPOSE 5000
COPY requirements*.txt ./
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]