django初始化后一些常规重置工作
配置重置
1. 执行下面代码创建django的一个项目pt_edu:
django-admin startproject pt_edu
2.创建config包文件夹,在config包文件夹下创建两个py文件,分别为develop.py和product.py:
3.将下面的代码分别加入manage.py、asgi.py、wsgi.py替换:
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.settings') # 可以通过 环境变量PROJECT_PROFILE为develop或者 product,让django 加载不同的配置 profile = os.environ.get('PROJECT_PROFILE', 'develop') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.config.%s' % profile)
manage.py如下:
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.settings') # 可以通过 环境变量PROJECT_PROFILE为develop或者 product,让django 加载不同的配置 profile = os.environ.get('PROJECT_PROFILE', 'develop') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.config.%s' % profile) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
asgi.py如下:
""" ASGI config for pt_edu project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.settings') # 可以通过 环境变量PROJECT_PROFILE为develop或者 product,让django 加载不同的配置 profile = os.environ.get('PROJECT_PROFILE', 'develop') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.config.%s' % profile) application = get_asgi_application()
wsgi.py如下:
""" WSGI config for pt_edu project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.settings') # 可以通过 环境变量PROJECT_PROFILE为develop或者 product,让django 加载不同的配置 profile = os.environ.get('PROJECT_PROFILE', 'develop') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pt_edu.config.%s' % profile) application = get_wsgi_application()
4.测试环境默认加载 develop配置,生产环境需要设置环境变量进行启动:
[设置环境变量] windows: set PROJECT_PROFILE=product PowerShell: $env:PROJECT_PROFILE="product" linux: export PROJECT_PROFILE=product
5.develop.py配置参考如下:
from ..settings import * DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'PORT': '3306', } }
6.product.py配置参考如下(这个文件不能添加至git里面):
同develop.py就可以了。
原创文章请随便转载。愿和大家分享,并且一起进步。-- 江 coder