This is the 25th day of my participation in Gwen Challenge


The introduction

There are a lot of things to configure when developing Django on the Web, and it’s easy to forget about them. Here are some common configuration notes for you to check. Of course, we should also be able to consult official documents, after all, reading literature is also a skill.

The official documentation, https://docs.djangoproject.com/en/3.1/ref/settings


When configuring a Django project, print BASE_DIR yourself to see where the path points to, since you’ll be using this BASE_DIR multiple times. Get to know the BASE_DIR base directory so you can use it in other configurations.

# settings.py or develop.py
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

print(BASE_DIR)

# Take my personal example
# C:\Users\Administrator\Desktop\meiduo_project\meiduo_mall\meiduo_mall
Copy the code


Configuring the Development Environment

The project environment is generally divided into ** development environment and ** production environment.

  • Development environment: Used to write and debug project code.
  • Production environment: used for online deployment and operation of projects.


1. Create a configuration file

  1. Prepare the configuration file directory
    • Create a new package and name itsettings, as the configuration file directory
  2. Prepare development and production environment profiles
    • In the configuration packagesettingsIn, new developmentdevelop.pyAnd productionproduct.pyEnvironment profile
  3. Prepare the development environment configuration
    • Will default to the configuration filesettings.pyCopy the content todevelop.py, product.py


2. Specify the development environment configuration file

Change this to the following in manage.py under the project

os.environ.setdefault("DJANGO_SETTINGS_MODULE"."meiduo_mall.settings.develop")
Copy the code


#! /usr/bin/env python
import os
import sys

if __name__ == "__main__":
    Set the development environment configuration file here
    os.environ.setdefault("DJANGO_SETTINGS_MODULE"."meiduo_mall.settings.develop")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            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?"
            )
        raise
    execute_from_command_line(sys.argv)

Copy the code


3. Specify the production environment configuration file

Change this to the following in uwsgi.py under the project:

import os

from django.core.wsgi import get_wsgi_application

Set the production environment profile here
os.environ.setdefault("DJANGO_SETTINGS_MODULE"."meiduo_mall.settings.product")

application = get_wsgi_application()
Copy the code


Note: The production environment configuration file is the same as the development environment and will need to be modified when the project is deployed.


Configure the Jinja2 template engine

Replace Django’s default template engine with the Jinja2 template engine.


1. Install the Jinja2 extension package

pip install Jinja2
Copy the code


2. Configure the Jinja2 template engine

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2'.# jinja2 template engine
        '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',],},},]Copy the code


3. Add the Jinja2 template engine environment

1. Create a new oneutilsThe Python package then creates the Jinja2 template engine environment configuration filejinja2_env.py


2, write the Jinja2 template engine environment configuration code

# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @desc: {Jinja2 template engine environment configuration module}
# @Date: 2021/05/20 16:33

from jinja2 import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse


Make sure you can use statements like {{url('')}} {{static('')}} in the template engine
def jinja2_environment(**options) :
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
    })
    return env
Copy the code


3. Load the Jinja2 template engine

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2'.# jinja2 template engine
        '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',].# Add Jinja2 template engine environment
            'environment': 'meiduo_mall.utils.jinja2_env.jinja2_environment',}},]Copy the code


Database Configuration

In the setting.py module, locate the DATABASES configuration option to configure

SQLite3 (default)

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


MySQL

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql'.MySQL database engine
        'HOST': '127.0.0.1'.# database address, local IP address 127.0.0.1
        'PORT': 3306.# database port
        'USER': 'root'.Database user name
        'PASSWORD': '123456'.# database password
        'NAME': 'BMSTest'.# database name}}Copy the code


The database ENGINE

The database engine to use. The built-in database engine includes:

  • 'django.db.backends.postgresql'
  • 'django.db.backends.mysql'
  • 'django.db.backends.sqlite3'
  • 'django.db.backends.oracle'


Static file directory

The STATICFILES_DIRS option is not available in djangos setting.py configuration file by default, so you need to manually add the STATICFILES_DIRS option to the setting file

# set the url prefix to access static files
STATIC_URL = '/static/'

# set the directory for storing static files
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
Copy the code


internationalization

LANGUAGE_CODE = 'en-us' # English

# TIME_ZONE = 'UTC' # Universal time

LANGUAGE_CODE = 'zh-hans'		# in Chinese

TIME_ZONE = 'Asia/Shanghai'		# China time zone

USE_I18N = True

USE_L10N = True

USE_TZ = True
Copy the code


Cache configuration

Add the CACHES configuration item in setting.py

# Django cache configuration
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',}}Copy the code

BACKEND

The cache back end to use. The built-in cache backend includes:

  • 'django.core.cache.backends.db.DatabaseCache'
  • 'django.core.cache.backends.dummy.DummyCache'
  • 'django.core.cache.backends.filebased.FileBasedCache'
  • 'django.core.cache.backends.locmem.LocMemCache'
  • 'django.core.cache.backends.memcached.MemcachedCache'
  • 'django.core.cache.backends.memcached.PyLibMCCache'

BACKEND can be set to a fully qualified path for caching BACKEND classes, that is, a caching BACKEND that does not come built-in with Django can be used


Django – Redis – Session configuration

Change Django’s default cache to Redis cache, and change the session storage mechanism to Redis cache

Reference: Django-Redis Chinese documentation https://django-redis-chs.readthedocs.io/zh_CN/latest/


1, install,django-redisExpansion pack,

pip install django-redis==4.4. 0
Copy the code


It is best to specify the Django version when installing the extension. Otherwise, it will install the latest version of Django, causing it to be incompatible with the Django version, and it will automatically uninstall the old version of Django and install the corresponding version. This breaks the Django development environment you prepared earlier.

  • Django - redis 3.8 xsupportDjango 1.4, 1.5, 1.6, 1.7(Maybe 1.8)
  • Django - redis 4.4 xsupportDjango 1.6, 1.7, 1.8, 1.91.10

For details, see the Django-redis Document https://django-redis-chs.readthedocs.io/zh_CN/latest/


2. Configure Redis database

# cache
CACHES = {
    Redis library 0 is used by default.
    "default": {
        "BACKEND": "django_redis.cache.RedisCache"."LOCATION": "Redis: / / 127.0.0.1:6379/0"."OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",}},# session, using the # 1 Redis library
    "session": {
        "BACKEND": "django_redis.cache.RedisCache"."LOCATION": "Redis: / / 127.0.0.1:6379/1"."OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",}}}Copy the code

Use the Redis database as Django’s cache database


Example Change the session storage mechanism to Redis cache

Configure Session storage
SESSION_ENGINE = "django.contrib.sessions.backends.cache"

# session Cache alias
SESSION_CACHE_ALIAS = "session"
Copy the code

SESSION_ENGINE and SESSION_CACHE_ALIAS are configured, and Session information is stored in the Redis database.


Configuring Project Logs

Configure the project log by setting the LOGGING option in the develop.py development environment.

LOGGING = {
    'version': 1.'disable_existing_loggers': False.# Whether to disable an existing logger
    'formatters': {  Format of log information display
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'}},# Filter logs
    'filters': {  
        'require_debug_true': {  # Django only outputs logs in debug mode
            '()': 'django.utils.log.RequireDebugTrue',}},# Log handling methods
    'handlers': {
        
        Output logs to the terminal
        'console': {  
            'level': 'INFO'.'filters': ['require_debug_true'].'class': 'logging.StreamHandler'.'formatter': 'simple'
        },
        
        Output logs to a file
        'file': {  
            'level': 'INFO'.'class': 'logging.handlers.RotatingFileHandler'.# Log file location
            'filename': os.path.join(os.path.dirname(BASE_DIR), 'logs/meiduo.log'),  
            'maxBytes': 300 * 1024 * 1024.'backupCount': 10.'formatter': 'verbose'}},# logger
    'loggers': {  
        'django': {  # define a logger named Django
            'handlers': ['console'.'file'].Log to terminal and file at the same time
            'propagate': True.# Whether to continue sending log information
            'level': 'INFO'.The lowest log level received by the logger}}},Copy the code


Prepare the log file directory

Create a directory for storing log files based on your LOGGING configuration

The location where the log file is stored
'filename': os.path.join(os.path.dirname(BASE_DIR), 'logs/meiduo.log'),
Copy the code


Use of the logger

import logging

Create logger
logger = logging.getLogger('django')

# output log
logger.debug('Test logging module debug')
logger.info('Test Logging module info')
logger.error('Test Logging module error')
Copy the code


Other configuration

Configure the login URL
LOGIN_URL='/user/login' # /accounts/login? next=/user

# Set djangos file storage class
DEFAULT_FILE_STORAGE='utils.fdfs.storage.FDFSStorage'

# set the path to the client.conf file used by FDFS
FDFS_CLIENT_CONF='./utils/fdfs/client.conf'

# set the IP and port number of nginx on FDFS storage server
FDFS_URL='http://172.16.179.131:8888/'
Copy the code