gpt4 book ai didi

django - 如何防止Django将管理URI覆盖到/admin而不是/api/admin/

转载 作者:行者123 更新时间:2023-12-02 12:14:44 28 4
gpt4 key购买 nike

正在将Django API放入Kubernetes中。

任何发送到/ Controller 的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: /$1
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会加载react前端。

导航到 192.168.99.105/api/auth/test/,将我带到“Hello World!”回应我迅速整理。

但是,当我尝试转到 192.168.99.105/api/admin时。如果删除了 /admin/login/?next=/admin/,它会自动将我重定向到不存在的 /api是否有防止这种行为的方法?

我也尝试过这个:

ingress-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),
]

只是产生“未找到”。

我也尝试使用 the documentation中显示的这种模式作为前缀:
urlpatterns = [
path('api/', include([
path('auth/', include('authentication.urls'), name='auth'),
path('admin/', admin.site.urls),
])),
]

但这只是使它成为 /api/api

以下是在 admin/中为 site-packages/django/contrib/admin/sites定义的路由:
# 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,因为它不再为管理门户提供 Assets :
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 - 如何防止Django将管理URI覆盖到/admin而不是/api/admin/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492071/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com