feat: 支持从环境变量配置数据库

- 添加 os 模块导入
- DEBUG 和 ALLOWED_HOSTS 从环境变量读取
- DATABASE_URL 支持 PostgreSQL 和 SQLite
- 默认使用 SQLite 便于部署
This commit is contained in:
maoshen
2026-04-12 22:06:04 +00:00
parent 3a01b98860
commit 89e8589e87
2 changed files with 27 additions and 12 deletions

View File

@@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
""" """
from pathlib import Path from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
@@ -23,9 +24,9 @@ BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-vvuexg2$gadudvj18-24xf3m$7f=8+ugtl&o@r_vgso)@#^$l2' SECRET_KEY = 'django-insecure-vvuexg2$gadudvj18-24xf3m$7f=8+ugtl&o@r_vgso)@#^$l2'
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = os.environ.get('DEBUG', 'True').lower() == 'true'
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '*').split(',')
# Application definition # Application definition
@@ -83,16 +84,29 @@ WSGI_APPLICATION = 'city_manual.wsgi.application'
# Database # Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases # https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = { import os
DATABASE_URL = os.environ.get('DATABASE_URL', '')
if DATABASE_URL.startswith('postgres'):
DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.postgresql', 'ENGINE': 'django.db.backends.postgresql',
'NAME': 'cssc', 'NAME': DATABASE_URL.split('/')[-1].split('?')[0],
'USER': 'coder', 'USER': DATABASE_URL.split('@')[0].split('/')[-1].split(':')[0],
'PASSWORD': '825670wl', 'PASSWORD': DATABASE_URL.split('@')[0].split(':')[-1],
'HOST': '10.2.0.100', 'HOST': DATABASE_URL.split('@')[1].split(':')[0],
'PORT': '5432', 'PORT': DATABASE_URL.split('@')[1].split(':')[-1].split('?')[0],
}
}
else:
# 默认使用 SQLite
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
} }
}
# Password validation # Password validation

View File

@@ -64,7 +64,8 @@ DJANGO_SETTINGS_MODULE=config.settings.production
DJANGO_SECRET_KEY=cssc-secret-key-$(date +%s) DJANGO_SECRET_KEY=cssc-secret-key-$(date +%s)
DEBUG=False DEBUG=False
ALLOWED_HOSTS=cssc.datalibstar.com,127.0.0.1,localhost ALLOWED_HOSTS=cssc.datalibstar.com,127.0.0.1,localhost
DATABASE_URL=postgres://coder:825670wl@10.2.0.100:5432/cssc # 临时使用 SQLite后续配置可访问的 PostgreSQL
DATABASE_URL=sqlite:///db.sqlite3
MEDIA_ROOT=/home/ubuntu/city-manual/backend/media MEDIA_ROOT=/home/ubuntu/city-manual/backend/media
STATIC_ROOT=/home/ubuntu/city-manual/backend/static STATIC_ROOT=/home/ubuntu/city-manual/backend/static
EOF EOF