"" " Here Case project called luffy create a virtual environment for luffy Project >: mkvirtualenv luffy " "" "" " (execute in cmd) installed by basic environment dependent >: PIP install Django 2.0.7 == >: PIP djangorestframework install >: PIP install pymysql "" "
Create a virtual project environment:
Install Django
Installation djangorestframework
Installation pymysql
"" " 1. General will create a folder for the project: >: # cd Desktop cut to the desktop >: mkdir luffy # create items stored in the desktop folder 2. Go to the project folder >: cd luffy 3. In the project file create a folder under the project, where the project named luffyapi >: Django-ADMIN startproject luffyapi development: open the project with pycharm, and select in advance the prepared virtual environment . "" "
"" " ├── luffyapi when ├── logs / # runtime of the project / development log directory - the folder ├── manage.py # script file ├── luffyapi / # project main application code to save development time - package ├── apps / # save directory developer's code to the module [sub-applications] the directory stores - package ├── libs / # save directory of third-party libraries [third party components, modules] - packet ├── settings / # configuration directory - package local configuration when the project development ├── dev.py # runtime line └── prod.py # project configuration ├── urls.py # total route └── utils / # plurality of modules [sub-applications] public function library [components to develop their own] script file when └── scripts / # save the project operator - folder "" "
"" " 1. Modify wsgi.py manage.py with two files: os.environ.setdefault ( 'the DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') 2. The removed or renamed settings.py, copy the contents of settings / in dev.py 3. modify dev.py file contents LANGUAGE_CODE = 'Hans-ZH' TIME_ZONE = 'Asia / of Shanghai' USE_TZ = False 4. modify the startup configuration: see illustration below whether the test 5. test default configuration file dev.py file: - method 1: test default in any __init__.py file if the configuration file is dev.py file from django.conf Import Settings Print (Settings) - 2: create t_dg.py tested in the folder scripts in file (see below details the test code) . "" "
scripts/t_dg.py
import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffyapi.settings.dev") django.setup() from django.conf import settings print(settings) # <Settings "luffyapi.settings.dev"> 成功配置
illustration
dev.py
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(module)s %(lineno)d %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler ' , ' Formatter ' : ' Simple ' }, ' File ' : { # actual development is recommended to use the WARNING ' Level ' : ' the INFO ' , ' class ' : ' logging.handlers.RotatingFileHandler ' , # log locations, log file name, save the log directory must be created manually, Note: this file path should pay attention to bASE_DIR it represents small luffyapi ' filename ' : os.path.join (os.path.dirname (bASE_DIR), "logs", " Luffy.log " ), # log file maximum, where we set 300M ' MaxBytes ' : 300 * 1024 * 1024 , # number of log files, set the maximum number of logs for 10 ' BACKUPCOUNT ' : 10 , # log format : verbose ' Formatter ' : ' verbose ' , # document content encoding ' encoding ' : ' UTF-. 8 ' }, }, # log object ' Loggers ': { ' Django ' : { ' handlers ' : [ ' Console ' , ' File ' ], ' the Propagate ' : True, # whether to allow logging to continue to bubble to the other information log processing system } } }
dev.py
# Environment variable operation: Small luffyapi BASE_DIR with apps folder to be added to the environment variable Import SYS sys.path.insert (0, base_dir) APPS_DIR = os.path.join (base_dir, ' apps ' ) # get apps absolute path sys.path.insert (1, APPS_DIR)
import logging logger = logging.getLogger('django')
from rest_framework.views import exception_handler as drf_exception_handler from rest_framework.views import Response from rest_framework import status from utils.logging import logger def exception_handler(exc, context): response = drf_exception_handler(exc, context) if response is None: logger.error('%s - %s - %s' % (context['view'], context['request'].method, exc)) return Response({ 'detail': '服务器错误' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True) return response
from rest_framework.response import Response class APIResponse(Response): def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs): data = { 'status': data_status, 'msg': data_msg, } if results is not None: data['results'] = results data.update(kwargs) super().__init__(data=data, status=http_status, headers=headers, exception=exception)