美文网首页
2.项目的基础配置

2.项目的基础配置

作者: 思绪太重_飘不动 | 来源:发表于2019-10-15 13:30 被阅读0次

    1.配置mysql数据库

    # 1.安装mysql
    pip install pymysql
    # 2.在工程的__init__.py中注册mysql
    import pymysql
    
    pymysql.install_as_MySQLdb()
    # 3.在settings.py中配置mysql数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',   # 使用mysql引擎
            'NAME': 'axf_db',    # 数据库名字
            'USER': 'root',        # 用户名称
            'PASSWORD': '123456',  # mysql密码
            'HOST': '127.0.0.1',    # 域名
            'PORT': 3306    # 端口
        }
    }
    
    # mysql常用命令
        show databases;           查看数据库
        create database  db_name  charset='utf-8';   创建数据库
        drop database db_name;   删除数据库
    

    2.rest-framework配置

    # 1.安装django-rest-framework 和 django-fliter
        pip install djangorestframework
        pip install django-filter  
    # 2.在settins.py中的配置
      INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',  # 添加rest-framework应用
    ]
    
    # 3.rest-framework的分页, 过滤, 重构配置
    # rest_framework配置
    REST_FRAMEWORK = {
        # 分頁配置
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 10,
        # 过滤
        'DEFAULT_FILTER_BACKENDS': (
            'django_filters.rest_framework.DjangoFilterBackend'
        ),
        # 重构renderer
        'DEFAULT_RENDERER_CLASSER': (
            'utils.renderer.MyJsonRenderer',
        )
    }
    

    3.日志配置

    # 1.在项目中创建 logs 包来存放日志文件
    # 2.在项目中创建utils工具包用来存放自己封装的工具文件
    # 3.在utlis中创建LogMiddleware.py文件来写日志中间键
    # 4.LogMiddleware.py中间键的内容
    import logging
    from datetime import datetime
    
    from django.utils.deprecation import MiddlewareMixin
    
    logger = logging.getLogger()
    
    
    class LogMiddle(MiddlewareMixin):
    
        def process_request(self, request):
            # 请求进来的时间
            request.init_time = datetime.now()
    
        def process_response(self, request, response):
            try:
                # 耗时多长
                count_time = datetime.now() - request.init_time
                # 请求方式
                method = request.method
                # 请求地址
                path = request.path
                # 响应状态码
                status_code = response.status_code
                # 相应内容
                content = response.content
    
                logger.info("%s %s %s %s %s" % (count_time, method, path,
                                                status_code, content ))
            except Exception as e:
                logger.critical('系统错误, %s' % e)
    
            return response
    
    # 在settins.py中的配置
    # 配置中间键
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'utils.LogMiddleware.LogMiddle',  # 日志中间键
    ]
    
    #日志配置文件
    # 在项目中创建一个logs的文件夹
    LOG_PATH = os.path.join(BASE_DIR, 'logs')
    LOGGING = {
        # 必须是1
        'version': 1,
        # 是否禁用日志, 默认为True
        'disable_existing_loggers': False,
        # 定义formatters组件,定义存储日志的格式
        'formatters': {
            'default': {
                'format': '%(levelno)s %(name)s %(asctime)s %(message)s'
            }
        },
        # 定义logger组件,用于接收日志信息
        'loggers': {
            '': {
                'handlers': ['console'],
                'level': 'INFO'
            }
        },
        # 定义handlers组件,用户写入日志信息
        'handlers': {
            'console': {
                'level': 'INFO',
                # 定义存储日志的文件
                'filename': '%s/log.txt' % LOG_PATH,
                # 指定写入日志中信息的格式
                'formatter': 'default',
                # 指定日志文件超过5M就自动备份
                'class': 'logging.handlers.RotatingFileHandler',
                'maxBytes': 5 * 1024 * 1024,
            }
        }
    }
    

    3. 中文配置

    # 语言设置默认'en-us'英语, 改成中文 zh-hans
    LANGUAGE_CODE = 'zh-hans'
    # 时区,默认UTC,改为中国上海时区Asia/Shanghai
    TIME_ZONE = 'Asia/Shanghai'
    

    4.配置reids缓存

    # 配置django-redis,用缓存
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379",  # 服务器地址
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                # "CONNECTION_POOL_KWARGS": {"max_connections": 100}#最大连接数
                # "PASSWORD": "密码",
            }
        }
    }
    

    5.其他配置,以后再加

    # sttings.py大致配置
    """
    Django settings for axf project.
    
    Generated by 'django-admin startproject' using Django 2.0.5.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/2.0/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.0/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '@0^_gbpymhwlql=w779@98duo2%$%n$&_m99bii@2cs9!=*v40'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = ["*"]
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # 'corsheaders',  # 跨域应用
        'rest_framework',  # 添加rest-framework应用
        # 配置项目应用
        'user',
        'goods',
        'carts',
        'orders',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        # 'corsheaders.middleware.CorsMiddleware',  # 跨域中间键
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'utils.LogMiddleware.LogMiddle',  # 日志中间键
    ]
    
    ROOT_URLCONF = 'axf.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            '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',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'axf.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    # 配置mysql数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'axf_db',
            'USER': 'root',
            'PASSWORD': '123456',
            'HOST': '127.0.0.1',
            'PORT': 3306
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    # 语言设置默认'en-us'英语, 改成中文 zh-hans
    LANGUAGE_CODE = 'zh-hans'
    # 时区,默认UTC,改为中国上海时区Asia/Shanghai
    TIME_ZONE = 'Asia/Shanghai'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    
    STATIC_URL = '/static/'
    
    
    # 跨域配置
    # 跨域允许的请求方式,可以使用默认值,默认的请求方式
    CORS_ALLOW_METHOSD = (
        'GET',       # 查询
        'POST',      # 创建
        'PUT',       # 修改
        'PATCH',     # 修改
        'DELETE',    # 删除
        'OPTIONS',
    )
    
    # 允许的跨域请求头,可以使用默认值,默认的请求头为:
    # from corsheaders.defaults import default_headers
    # CORS_ALLOW_HEADERS = default_headers
    
    CORS_ALLOW_HEADERS = (
        'XMLHttpRequest',
        'x_FILENAME',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
        'Pragma',
    )
    
    # 跨域求请时,是否运行携带cookie,默认为False
    CORS_ALLOW_CREDENTIALS = True
    
    # 允许所有主机执行跨站点请求,默认为False
    # 如果没设置参数,则必须设置白名单,运行部分白名单的主机才能执行跨站点请求
    CORS_ORIGIN_ALLOW_ALL = True
    
    # 配置django-redis,用缓存
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379",  # 服务器地址
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                # "CONNECTION_POOL_KWARGS": {"max_connections": 100}#最大连接数
                # "PASSWORD": "密码",
            }
        }
    }
    
    
    # rest_framework配置
    REST_FRAMEWORK = {
        # 分頁配置
        # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
        # 'PAGE_SIZE': 10,
        # 过滤
        'DEFAULT_FILTER_BACKENDS': (
            'django_filters.rest_framework.DjangoFilterBackend'
        ),
        # 重构renderer
        'DEFAULT_RENDERER_CLASSER': (
            'utils.renderer.MyJsonRenderer',
        )
    }
    
    # 日志配置
    # 在项目中创建一个logs的文件夹
    LOG_PATH = os.path.join(BASE_DIR, 'logs')
    LOGGING = {
        # 必须是1
        'version': 1,
        # 是否禁用日志, 默认为True
        'disable_existing_loggers': False,
        # 定义formatters组件,定义存储日志的格式
        'formatters': {
            'default': {
                'format': '%(levelno)s %(name)s %(asctime)s %(message)s'
            }
        },
        # 定义logger组件,用于接收日志信息
        'loggers': {
            '': {
                'handlers': ['console'],
                'level': 'INFO'
            }
        },
        # 定义handlers组件,用户写入日志信息
        'handlers': {
            'console': {
                'level': 'INFO',
                # 定义存储日志的文件
                'filename': '%s/log.txt' % LOG_PATH,
                # 指定写入日志中信息的格式
                'formatter': 'default',
                # 指定日志文件超过5M就自动备份
                'class': 'logging.handlers.RotatingFileHandler',
                'maxBytes': 5 * 1024 * 1024,
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2.项目的基础配置

          本文链接:https://www.haomeiwen.com/subject/gwvjmctx.html