我几乎什么都试过了,从研究到研究.基本上,我有我的前端服务器和后端服务器.我的前端服务器从运行Django的后端服务器收到错误.

这是我在Django应用程序中的设置

"""
Django settings for appliAI project.

Generated by 'django-admin startproject' using Django 4.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'removed because I am not giving that out'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

# asdf.com has is replacing my actual URL

ALLOWED_HOSTS = [
    "localhost",
    "127.0.0.1",
    "asdf.com",
    "*.asdf.com",
]

# Application definition

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sslserver',
    'django_extensions',
    'rest_framework',
]
# Access-Control-Allow-Credentials = 
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
    
    # 'whitenoise.middleware.WhiteNoiseMiddleware',
]

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^https://\w+\.asdf\.com$",
]

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_DEBUG = True
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]


APPEND_SLASH=False

CORS_ALLOW_CREDENTIALS = False



ROOT_URLCONF = 'appliAI.urls_ssl'

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 = 'appliAI.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/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.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

SSL_CERTIFICATE_PATH = 'removed for security reassons'
SSL_PRIVATE_KEY_PATH = 'removed for security reassons'

这是我的前端文章

axios.post(appliAiUrl + '/getPredictions',
 {
   "username"            : username,
   "company_code"   : company_code,
   "company_id" : company_id
 }
 )
 .then(response => response.data)
 .then(data => {
  processRecommendation(data);
 })

我将nginx设置为反向代理服务器,我有这个https://127.0.0.1:8000

我没有什么可以try 的东西了,我真的不想让所有人都访问我的服务器.

我基本上已经try 了我能想到的所有方法,试图让这件事奏效.这是我的睡衣

       location / {
                proxy_pass https://127.0.0.1:8000;
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

我以为添加CORS_ALLOW_ALL_RESOURCES=True会让我达到一个可以工作的状态,但我错了.我也真的不想那样做.

错误消息

CORS策略已阻止从源‘appli.asdf.com’访问位于‘appliai.asdf.com/getPredictions’的XMLHttpRequest.:对印前判断请求的响应未通过访问控制判断:请求的资源上不存在‘Access-Control-Allow-Origin’标头.Xhr.js:220 post appliai.asdf.com/getPredictions net::Err_FAILED

我暂时负责这项工作,直到我能解决所有的问题.

python3 manage.py runserver_plus --cert /etc/nginx/ssl/asdf_com/__asdf_com.crt --key /etc/nginx/ssl/asdf.key

2023-12-30 05:31:49.514533: I external/local_tsl/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
2023-12-30 05:31:50.203226: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2023-12-30 05:31:50.203517: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2023-12-30 05:31:50.397149: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-12-30 05:31:50.859038: I external/local_tsl/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
2023-12-30 05:31:50.860671: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-12-30 05:31:52.648624: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
Using TensorFlow backend
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on https://127.0.0.1:8000
Press CTRL+C to quit
 * Restarting with stat
Performing system checks...

2023-12-30 05:31:59.266727: I external/local_tsl/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
2023-12-30 05:32:00.448743: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2023-12-30 05:32:00.449008: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2023-12-30 05:32:00.709272: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-12-30 05:32:01.259375: I external/local_tsl/tsl/cuda/cudart_stub.cc:31] Could not find cuda drivers on your machine, GPU will not be used.
2023-12-30 05:32:01.270345: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-12-30 05:32:03.106345: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
Using TensorFlow backend
System check identified no issues (0 silenced).

Django version 4.2.7, using settings 'asdf.settings'
Development server is running at https://[127.0.0.1]:8000/
Using the Werkzeug debugger (https://werkzeug.palletsprojects.com/)
Quit the server with CONTROL-C.
 * Debugger is active!
 * Debugger PIN: 479-017-511


当我try 点击API时,当我应该看到这样的东西时,什么也没有出现

1/1 [==============================] - 0s 72ms/step
1/1 [==============================] - 0s 23ms/step

推荐答案

经过多次反复try ,最终还是采用了Nginx和Gunicorn的组合(HTTPS和HTTPS).

当通过Gunicorn运行Django应用程序时,它默认监听HTTP,而不是HTTPS.我需要一种方法来传递一个代理,这样我用来访问API的URL就可以使用HTTPS而不是HTTP.

Nginx配置:

server {
        listen 443 ssl;
        server_name     www.test.com;
        root         /var/www;


        ssl_certificate_key /etc/nginx/ssl/test.key;
        ssl_certificate /etc/nginx/ssl/test_com/__test_com.crt;
        index index.html index.htm index.nginx-debian.html;

        location / {
                proxy_pass http://localhost:8000;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
        }
}

有一个Django设置我需要更改,那就是在允许的主机中.

允许的主机=[ 我是说,"本地主持人" -"127.0.0.1", "*.est.com", "asdf.test.com","asdf.test.com", =引用=

我必须指定实际的子域.仅仅使用*.est.com根本不起作用.

Django相关问答推荐

如何使用Django';S生成的字段来统计相关对象?

""关系"core_Boundary_summary的列user_id中的空值"违反了非空约束|失败行包含(2,title,string,null)

Django ORM ForeignKey查询使用注释设置输出

新的 Django 开发人员无法在网站上显示Hello World,而不是默认安装成功页面

使用OuterRef过滤器获取Django记录的最大值

如何在两个字段上查找 django 模型的副本?

CsrfViewMiddleware 和 enforce_csrf 有什么区别?

过滤查询以获取两个朋友之间的聊天消息?

从一个组中获取所有用户 - Django

删除所有实例后,Django 模型实例主键不会重置为 1

验证 Django 模型对象的正确方法?

为什么 django 1.7 会为字段 Select 的变化创建迁移?

在 Django CharFields 中自动截断 max_length 字段

如何在 django 模板中将名称反转为绝对 url?

使用 Python / Django 的 Google API 示例的 Oauth

Matplotlib - Tcl_AsyncDelete:异步处理程序被错误的线程删除?

如何在 django 元素中开始做 TDD?

Django:以 10 为底的 int() 的无效文字

Django Admin:如何在内联中显示模型上定义的属性?

ModelForm 上的 Django 和字段集