01 DEBUG debug configuration
Development period is set to True, False is set to publish
02 INSTALLED_APPS installed APP configuration
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', # drf 框架 'Applications.Organization.apps.OrganizationConfig', # Organization APP 'GeneralTools', # 常用工具 ]
03 TEMPLATES template configuration
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'Applications/Organization/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', ], }, }, ]
04 Set IP database variables
MYSQL_SERVER = '49 .235.156.156 ' REDIS_SERVER = '49 .235.156.156' FDFS_SERVER = '49 .235.156.156 '
05 DATABASES Database Configuration
05.1 sqlLite database configuration (the default configuration)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
05.2 mysql database configuration
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yiwenzhen_db', 'USER': 'root', 'PASSWORD': 'ws$RV^TM0okm20200203', 'HOST': MYSQL_SERVER, 'PORT': '3306', # 'OPTIONS': { # "init_command": "SET sql_mode='STRICT_TRANS_TABLES'", # } } }
05.3 redis database configuration
# Redis 数据库 CACHES = { # 缓存view数据 "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://" + REDIS_SERVER + ":6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "1q2w3e", } }, # 缓存登录session "session": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://" + REDIS_SERVER + ":6379/1", "OPTIONS": { "CLIENT_CLASS ":" django_redis.client.DefaultClient ", # codes stored sms } " PASSWORD ":" 1q2w3e ", }, "sms_codes": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "Redis: //" + REDIS_SERVER + ": 6379/2", "the OPTIONS": { "CLIENT_CLASS" : "django_redis.client.DefaultClient", "PASSWORD": "1q2w3e", } } } # Django modified redis save mechanism uses the Session, and using the name 'session' is redis configuration. # Here to modify Django's Session mechanism for storing primarily to give Admin site uses. = SESSION_ENGINE "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "the session"
05.4 fastDFS database configuration
# Storage file specified by default cover Django DEFAULT_FILE_STORAGE = 'Tools.storage.FdfsStorage' # custom two variables, respectively, and the path fdfs client.conf file URL FDFS_CLIENT_CONF = the os.path.join (base_dir, 'the Configurations' , 'client.conf') FDFS_URL = 'HTTP: //' + + FDFS_SERVER ': 80 /'
06 date language settings
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai'
07 static files directory configuration
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
08 arranged for automatic log generation
# Log processing the LOGGING = { 'Version':. 1, 'disable_existing_loggers': False, # whether to disable the existing logger ' formatters': format {# display the log message 'verbose': { 'the format': '% (levelname ) S% (the asctime) S% (Module1) S% (lineno) D% (Message) S ' }, ' Simple ': { ' the format ':'% (levelname) S% (Module1) S% (lineno) D % (Message) S ' }, }, ' filters': filtering the log {# 'require_debug_true': {# django output log only debug mode '()': 'django.utils.log.RequireDebugTrue', } , }, 'handlers':{# Log processing method 'console': {# terminal to the output log 'level': 'INFO', 'Filters': [' require_debug_true '], ' class': 'logging.StreamHandler', 'Formatter': 'Simple' }, 'File': {# output to a log file in the 'Level': 'the INFO', 'class ':' logging.handlers.RotatingFileHandler ', ' filename ': the os.path.join (base_dir,' 'position, the log file # config / yiwenzhen.log) ' MaxBytes': 1024 * 1024 * 300, 'BACKUPCOUNT': 10, 'Formatter': 'verbose' }, }, 'Loggers': # {logger 'yiwenzhen': 'level': 'INFO', the lowest logs received by the log rank #{# Define a named yiwenzhen logger, 'handlers': [ 'console' , 'file'], # may be simultaneously output to the terminal log file 'propagate': True, # whether to transfer log information } } }
09 DRF Configuration
# Configure the REST REST_FRAMEWORK = { # the JWT authentication 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', the JWT authentication # 'rest_framework.authentication.SessionAuthentication', # session authentication 'rest_framework.authentication.BasicAuthentication', # basic authentication ), # filter filtering 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend',), # tab pagination # pagination also be custom class to add a different paging behavior of view. In view pagination_clas be indicated by the property. 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20 is, 'EXCEPTION_HANDLER': 'utils.exceptions.exception_handler', # 接口文档 # 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', }
10 Django model class specified authentication system used
10.1 Creating BaseModel.py file in GeneralTools
Models django.db Import from class BaseModel (models.Model): the create_time = models.DateTimeField (auto_now_add = True, the verbose_name = 'Created', help_text = 'Created') UPDATE_TIME = models.DateTimeField (auto_now = True, the verbose_name = 'update', help_text = 'updated') class Meta -: # Description this class is an abstract model classes, the table is not generated at the time of migration abstract = True
10.2 Open the Applications / Organization / models.py, create a model
Models django.db Import from from django.contrib.auth.models Import AbstractUser from GeneralTools.BaseModel Import BaseModel class the User (AbstractUser, BaseModel): OpenID = models.CharField (MAX_LENGTH = 100, the verbose_name = 'uniquely identify the micro-channel', null = true, blank = true, help_text = 'OpenID') Mobile = models.CharField (= 20 is MAX_LENGTH, the verbose_name = 'phone', help_text = 'phone') # pass the whole platform is a mobile phone identity = models.CharField (max_length = 30 , verbose_name = 'ID number', default = '', help_text = ' ID number') Weixin = models.CharField (= 50 MAX_LENGTH, verbose_name = 'microsignal', null = True, blank = True, help_text = ' micro signal ') nickname = models.CharField (= 200 is MAX_LENGTH, the verbose_name =' user nicknames ', null = True, blank = True, help_text ='Nickname ') True, help_text ='Nickname ') sexchoice = ( (1' M '), (2, 'F') ) Sex = models.IntegerField (= sexchoice choices, the verbose_name = 'Sex', null = True, blank = True, help_text = ' Sex') Province = Models .CharField (max_length = 30, verbose_name = ' save', null = True, blank = True, help_text = ' save') language = models.CharField (MAX_LENGTH = 100, the verbose_name = 'language', null = True, blank = True , help_text = 'language') City models.CharField = (= 30 MAX_LENGTH, the verbose_name = 'city', null = True, blank = True, help_text = ' city (city level)') Country = models.CharField (= MAX_LENGTH 30, verbose_name = 'county', null = True, blank = True, help_text = ' county (level city)') headimgurl = models.CharField (MAX_LENGTH = 300, the verbose_name = 'micro-channel path of head', null = True,blank = True, help_text = 'avatar micro-channel path') = models.CharField unionid (MAX_LENGTH = 100, the verbose_name = 'unionid', null = True, blank = True, help_text = 'unionid') subscribe_scene = models.CharField (max_length = 50, verbose_name = ' user-focused channel sources', null = True, blank = True, help_text =' user-focused channel sources') class Meta: db_table = 'UserInfo' verbose_name_plural = '001 user information table '
10.3 behind the increase in settings.py file
AUTH_USER_MODEL = 'Organization.UserInfo'
10.4 data migration
(venv) D:\DjangoDevelopment\projects\Tongheng2>python manage.py makemigrations Migrations for 'Organization': Applications\Organization\migrations\0001_initial.py - Create model UserInfo (venv) D:\DjangoDevelopment\projects\Tongheng2>python manage.py migrate Operations to perform: Apply all migrations: Organization, admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying Organization.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying sessions.0001_initial... OK (venv) D:\DjangoDevelopment\projects\Tongheng2>
CORS 11 Setting cross-domain whitelist
# CORS cross-domain whitelist CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:80', 'http://127.0.0.1:8000', ) CORS_ALLOW_CREDENTIALS allowed cookie = True #
12 JWT Configuration
# JWT configuration JWT_AUTH = { # setting generation (issued) when the effective time JWT token token 'JWT_EXPIRATION_DELTA': the datetime.timedelta (Days =. 1), # JWT specify extended response data generated call log view function 'JWT_RESPONSE_PAYLOAD_HANDLER': 'Apps.OrgsAndUsers .utils.jwt_response_payload_handler ' }
Response data generation function 13 JWT
13.1 utils.py create a file in the directory Organization
the logging Import # acquired logger defined in the configuration file for logging logger = logging.getLogger ( 'tongheng2') DEF jwt_response_payload_handler (token, User = None, Request = None): "" " Customize View log response data jwt "" " return { 'ID': the user.id, 'name': the user.name, 'PHOTO_URL': user.photo_url, 'role_flag': user.role_flag, 'Mobile': user.mobile, 'OpenID': User .openid, 'token': token }
13.2 Configuration increase in settings.py
# JWT configuration JWT_AUTH = { # setting generation (issued) when the effective time JWT token token 'JWT_EXPIRATION_DELTA': the datetime.timedelta (Days =. 1), # JWT specify extended response data generated call log view function 'JWT_RESPONSE_PAYLOAD_HANDLER': 'Applications.Organization .utils.jwt_response_payload_handler ' }
Django backend authentication system 14 designated class, for verifying the login
14.1 Open file directory created under the Organization utils.py, additions:
Re Import from django.contrib.auth.backends Import ModelBackend Import the logging from the UserInfo Applications.Organization.models Import Logger acquired defined in the configuration file # for logging Logger = logging.getLogger ( 'tongheng2') DEF jwt_response_payload_handler (token , User = None, Request = None): "" " custom response data view Log jwt " "" return { 'ID': the user.id, 'name': the user.name, 'PHOTO_URL': user.photo_url, ' role_flag ': user.role_flag, ' Mobile ': user.mobile, ' OpenID ': user.openid, ' token ':token } class UsernameMobileAuthBackend(ModelBackend): """ Custom Django authentication system back-end classes "" " DEF the authenticate (Self, Request, username = None, password = None, ** kwargs): " "" username: may be the phone number or letter openID micro login according to the phone number, you need to verify password The openID login, password authentication is not required, just enter a password "" " the try: IF re.match (R & lt '^. 1 [3-9] \ {D} $. 9', username): # The phone No. users query the user = UserInfo.objects.get (Mobile = username) # If the user exists, verify the password is correct IF IS not the user and user.check_password None (password): return the user the else: the user = None the else: # Micro letter openID user queries the User = UserInfo.objects.get (openid = username) # If the user exists, verify the password is correct IF IS not the User None: return the User the else: the User = None the except UserInfo.DoesNotExist: the User = None return the User
14.2 increase in settings.py configuration
# Specify the Django authentication system back-end classes, support user login name or phone number AUTHENTICATION_BACKENDS = [ # 'Apps.OrgsAndUsers.utils.UsernameMobileAuthBackend' ]
15 DRF extension
# DRF extended REST_FRAMEWORK_EXTENSIONS = { # buffer time in seconds (24 hours) 'DEFAULT_CACHE_RESPONSE_TIMEOUT': 24 * 60 * 60, # cache storage 'DEFAULT_USE_CACHE': 'default', }