django - 反向代理Nginx+Docker+Django项目后在本服务器上找不到请求的资源报错
问题描述
当我尝试访问localhost/auth/时遇到问题,这可能是由于 nginx 配置或可能是另一个其他问题。以下是我尝试向代理地址 localhost/auth/发出请求后从 nginx 日志中得到的结果
reverse-proxy | 0.0.0.0 - - [28/Aug/2020:08:21:47 +0000] "GET /api/ HTTP/1.1" 404 159 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
当我访问http://localhost/admin/时,Admin 登录页面按预期呈现,如下所示。同样在http://localhost/doc/上,redocs 文档页面也会呈现。
项目结构
├── nccggbot
│ ├── chatbot/
│ └── core/
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── settings.py
│ │ ├── urls.py
│ │ ├── wsgi.py
│ ├── static/
│ │ ├── admin/
│ │ ├── django_extensions/
│ │ |── drf-yasg
│ │ ├── rest_framework
│ │
│ ├── Dockerfile
│ ├── manage.py
│ ├── requirements.txt
│
│
├──reverse_proxy/
│ ├── default.conf
│ └── Dockerfile
├──docker-compose-deploy.yml
├──README.md
核心/urls.py
from django.contrib import admin
from django.urls import include,path
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions
from django.conf import settings
from django.conf.urls.static import static
schema_view = get_schema_view(
openapi.Info(
title="NCCG ChatBot API",
default_version='v1.0.0',
description="The nccg chatbot rest API",
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('admin/', admin.site.urls),
path('doc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
path('api-auth/', include('rest_framework.urls')),
path('api/', include('chatbot.urls'))
]
设置.py
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
DEBUG = bool(int(os.environ.get("DEBUG", default=0)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
ALLOWED_HOSTS = ['*']
# ALLOWED_HOSTS_ENV = os.environ.get('ALLOWED_HOSTS')
# if ALLOWED_HOSTS_ENV:
# ALLOWED_HOSTS.extend(ALLOWED_HOSTS_ENV.split(','))
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chatterbot.ext.django_chatterbot',
'rest_framework',
'drf_yasg',
'chatbot'
]
# ChatterBot settings
CHATTERBOT = {
'name': 'NCCG Support Bot',
'django_app_name': 'django_chatterbot'
}
MIDDLEWARE = [
'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': [],
'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'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
print(DEBUG)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
# if DEBUG is False:
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
# else:
# DATABASES = {
# "default": {
# "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
# "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")),
# "USER": os.environ.get("SQL_USER", "user"),
# "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
# "HOST": os.environ.get("SQL_HOST", "localhost"),
# "PORT": os.environ.get("SQL_PORT", "5432"),
# }
# }
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/static/'
MEDIA_URL = '/static/media/'
STATIC_ROOT = '/vol/web/static'
MEDIA_ROOT = '/vol/web/media'
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
NGINX 配置文件
upstream webserver {
server nccgbot-service:8000;
}
server {
listen 80;
gzip on;
location /auth {
proxy_pass http://webserver/api-auth;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
client_max_body_size 100M;
}
location /doc {
proxy_pass http://webserver/doc;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
client_max_body_size 100M;
}
location / {
proxy_pass http://webserver;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
client_max_body_size 100M;
}
location /static {
autoindex on;
alias /vol/static;
}
}
码头工人撰写文件
version: '3.7'
services:
# Chat bot
nccgbot-service:
container_name: nccgbot-service
image: nccgbot-service
build:
context: ./nccgbot_service
command: sh -c "python manage.py makemigrations && python manage.py collectstatic --no-input && python manage.py migrate && gunicorn core.wsgi:application --workers 2 --bind 0.0.0.0:8000"
volumes:
- static_data:/vol/web
env_file:
- ./.env
expose:
- "8000"
restart: on-failure
# proxies requests to internal services
reverse_proxy:
build:
context: ./reverse_proxy
restart: always
image: reverse-proxy
container_name: reverse-proxy
volumes:
- static_data:/vol/static
ports:
- "80:80"
depends_on:
- nccgbot-service
volumes:
static_data:
聊天机器人/urls.py
from django.conf.urls import url
from chatbot.views import ChatterBotApiView
urlpatterns = [
url(r'^chatbot/', ChatterBotApiView.as_view(), name='chatbot'),
]
**当我访问时浏览器输出localhost/api-auth
**
解决方案
rest_framework.urls 没有索引视图:
urlpatterns = [
url(r'^login/$', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'),
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
]
所以/auth/login
应该工作。此外,它不会做你认为它做的事情。这提供了 Django 的标准登录和注销视图,并且不通过 REST 进行身份验证。查看第三方软件包。并查看Django Vue Auth Demo以讨论在使用分离的前端通过 REST 进行身份验证时的一些常见错误和陷阱。
推荐阅读
- python - Python 帮助 - 尼姆游戏
- cloudkit - 如何使用 Cloudkit JS 保存 CLLocation
- javascript - 为什么不能在 instanceof HTMLInputElement 上使用“hasOwnProperty”?
- python - 如何合并两个熊猫数据框并保持重复值?
- python-3.x - 如何在多索引数据框中重新采样数据
- python-2.7 - 在 2020 年 Python 2 生命周期结束后,我还能通过 Pip 安装依赖包吗?
- php - Laravel 中的多重审批流程
- loops - 如何在谷歌工作表编辑器脚本中循环 getRange("B" + row + " :" + "J" + row)
- linux - 如何在 bash 中找到一些文件并将它们输入到另一个程序中?
- python-3.5 - AttributeError:模块 'shutil' 没有属性 'copy'