我正在尝试部署 Django 项目,但在网络上获取它时遇到了困难。让我回顾一下我目前遇到的问题:
我通过 SSH 连接到远程服务器并尝试在那里部署项目。我目前没有域名,所以现在我使用 IP 地址。
我已经设置了 Gunicorn 和 Nginx 并让它们运行,但是当我转到浏览器并尝试通过“https://...”访问该网站时,出现以下错误:
Request Method: GET
Request URL: http://**.**.***.***/
Using the URLconf defined in apegd_ai_core.urls, Django tried these URL patterns, in this order:
admin/
The empty path didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
[Unit]
Description=Gunicorn instance to serve application
After=network.target
[Service]
User=john
Group=john
WorkingDirectory=/home/john/graph_django/apegd_ai_core
ExecStart=/home/bobby/Documents/graph_project/vDect2/bin/gunicorn -w 4 -b 0.0.0.0:8007 --error-logfile /home/john/gra>
Environment="DJANGO_SECRET_KEY=encrptedsecretkey"
[Install]
WantedBy=multi-user.target
server {
listen 80;
server_name **.**.***.***;
location /static/ {
alias /home/jared/graph_django/apegd_ai_core/staticfiles;
}
location / {
proxy_pass http://127.0.0.1:8007;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 443 ssl;
server_name **.**.***.***;
location /static/ {
alias /home/jared/graph_django/apegd_ai_core/staticfiles;
}
ssl_certificate /etc/nginx/ssl/selfsigned.crt;
ssl_certificate_key /etc/nginx/ssl/selfsigned.key;
location / {
proxy_pass http://127.0.0.1:8007;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
from django.contrib import admin
from django.urls import include, path,re_path
urlpatterns = [
path("admin/", admin.site.urls),
path(" ",include('apegd_ai_core.urls')),
]
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
APEGHDAI_DIR = os.path.join(BASE_DIR, 'api', 'APEGHDAI')
# 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 = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['**.**.***.***']
CORS_ALLOW_ALL_ORIGINS = True
Traceback (most recent call last):
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 135, in>
self.handle_request(listener, req, client, addr)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 178, in>
respiter = self.wsgi(environ, resp.start_response)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 124>
response = self.get_response(request)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/core/handlers/base.py", line 140>
response = self._middleware_chain(request)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/core/handlers/exception.py", lin>
response = response_for_exception(request, exc)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/core/handlers/exception.py", lin>
response = handle_uncaught_exception(
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/core/handlers/exception.py", lin>
return debug.technical_500_response(request, *exc_info)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/views/debug.py", line 67, in tec>
html = reporter.get_traceback_html()
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/views/debug.py", line 410, in ge>
c = Context(self.get_traceback_data(), use_l10n=False)
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/views/debug.py", line 379, in ge>
"settings": self.filter.get_safe_settings(),
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/views/debug.py", line 154, in ge>
settings_dict[k] = self.cleanse_setting(k, getattr(settings, k))
File "/home/sidharth/Documents/graph_project/vDect2/lib/python3.8/site-packages/django/conf/__init__.py", line 111, in >
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
我的 SSL 密钥和证书均已设置并存在于 Nginx 目录中的 SSL 文件夹中。
当我运行“sudo systemctl status nginx”和“sudo systemctl status apegd.service”时,Nginx 和 Gunicorn 似乎都运行良好。
“$DJANGO_SECRET_KEY”被设置为环境变量,当我回显它时,终端会正确输出它。
总而言之,我很茫然,而且由于我以前从未部署过Django项目,所以我肯定很茫然,哈哈。有人知道为什么我无法从浏览器访问我的应用程序吗?非常非常感谢!
即使您能够从终端回显它,django 应用程序似乎在读取它时遇到问题。最佳实践是创建一个 .env 文件并将其放置在项目的根目录中(manage.py 所在的位置)。
使用新行中可能需要的每个键值对来构造 .env 文件。
DJANGO_SECRET_KEY=encryptedsecretkey
然后修改 settings.py 中的代码以从 .env 文件加载环境变量。另请注意来自
environ
库的额外导入 django-environ
(需要添加到您的要求并 pip install..)。以同样的方式加载您可能需要的其他环境变量..
from pathlib import Path
import os
import environ
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(
# set casting, default value
DEBUG=(bool, True)
)
# APEGHDAI_DIR = os.path.join(BASE_DIR, 'api', 'APEGHDAI')
# try this way instead of APEGHDAI_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# SECURITY WARNING: don't run with debug turned on in production
DEBUG = env('DEBUG')
# 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 = env('DJANGO_SECRET_KEY')
ALLOWED_HOSTS = ['**.**.***.***']
CORS_ALLOW_ALL_ORIGINS = True