Environment Setup
1. Virtual Environment Initialization
Isolate project dependencies to avoid conflicts with system-wide packages. While IDEs like PyCharm offer automatic setup, you can manually create one:
python -m venv venv
2. Dependency Installation
Specify framework versions to ensure consistency. This example uses Django 5.0.3 alongside Django REST Framework and database drivers.
pip install django==5.0.3
dpip install djangorestframework
pip install mysqlclient
pip install redis django-redis
3. Project Generation
Initialize the core project directory named initial_project.
django-admin startproject initial_project
Core Configuration Adjustments
1. Localization Settings
Update settings.py to set the language to Chinese and the timezone to Shanghai.
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
2. Database Integration
Replace the default SQLite configuration with MySQL. Comment out the original DATABASES block to keep a reference.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3. App Registration
Add third-party applications to INSTALLED_APPS to enable their functionality.
INSTALLED_APPS = [
# ... default apps
'rest_framework',
]
4. Redis Caching
Configure Redis for general caching and session storage. Place this configuration near the database settings for easy access.
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"}
},
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"}
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"
Directory and File Reorganization
1. Application Container
Create an applications directory inside the root to house custom Django apps. Update sys.path in settings.py so Python can locate these modules.
import sys
import os
APPS_DIR = os.path.join(BASE_DIR, 'applications')
sys.path.insert(0, APPS_DIR)
2. Environment Separation
Refactor the configuration to support multiple environments. Create a config directory inside the project root (initial_project).
- Move
settings.pyintoconfigand rename it toobase.py. - Create
development.pyandproduction.pyinsideconfig. - In
development.py, import everything from base:
from .base import *
Update manage.py to point to the development settings:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'initial_project.config.development')
Similarly, update wsgi.py for deployment scenarios.
3. Logging Strategy
Implement a robust logging configuration in base.py to output info to both the console and a rotating file.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR, '..', 'logs', 'app.log'),
'maxBytes': 1024 * 1024 * 50, # 50MB
'backupCount': 5,
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': True,
},
},
}
4. Template Directory
Create a top-level templates folder for HTML files. Ensure Django looks in this directory by updating the TEMPLATES setting in your config file:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '..', 'templates')],
'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',
],
},
},
]