zoukankan      html  css  js  c++  java
  • 后台Response和异常和日志封装、跨域问题及解决、es6的箭头函数、xadmin后台管理

    ## 1 后台Response和异常和日志封装

    ```python
    # utils/response

    from rest_framework.response import Response


    class APIResponse(Response):
    def __init__(self,code=1,msg='成功',result=None,status=None,headers=None,content_type=None,**kwargs):
    dic={
    'code':code,
    'msg':msg

    }
    if result:
    dic['result']=result
    dic.update(kwargs)

    #对象来调用对象的绑定方法,会自动传值
    super().__init__(data=dic,status=status,headers=headers,content_type=content_type)

    # 类来调用对象的绑定方法,这个方法就是一个普通函数,有几个参数就要传几个参数
    # Response.__init__(data=dic,status=status,headers=headers,content_type=content_type)
    ```

    ```python
    #utils/exceptions.py

    #方法,加日志

    from rest_framework.views import exception_handler
    # from luffyapi.utils import response
    from .response import APIResponse
    from .logger import log
    def common_exception_handler(exc, context):
    log.error('view是:%s ,错误是%s'%(context['view'].__class__.__name__,str(exc)))
    #context['view'] 是TextView的对象,想拿出这个对象对应的类名
    print(context['view'].__class__.__name__)
    ret=exception_handler(exc, context) # 是Response对象,它内部有个data

    if not ret: #drf内置处理不了,丢给django 的,我们自己来处理
    # 好多逻辑,更具体的捕获异常
    if isinstance(exc,KeyError):
    return APIResponse(code=0, msg='key error')

    return APIResponse(code=0,msg='error',result=str(exc))
    else:
    return APIResponse(code=0,msg='error',result=ret.data)


    ```

    ```python
    # 封装logger
    # setting.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': {
    # 实际开发建议使用WARNING
    'level': 'DEBUG',
    'filters': ['require_debug_true'],
    'class': 'logging.StreamHandler',
    'formatter': 'simple'
    },
    'file': {
    # 实际开发建议使用ERROR
    'level': 'INFO',
    'class': 'logging.handlers.RotatingFileHandler',
    # 日志位置,日志文件名,日志保存目录必须手动创建,注:这里的文件路径要注意BASE_DIR代表的是小luffyapi
    'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
    # 日志文件的最大值,这里我们设置300M
    'maxBytes': 300 * 1024 * 1024,
    # 日志文件的数量,设置最大日志数量为10
    'backupCount': 100,
    # 日志格式:详细格式
    'formatter': 'verbose',
    # 文件内容编码
    'encoding': 'utf-8'
    },
    },
    # 日志对象
    'loggers': {
    'django': {
    'handlers': ['console', 'file'],
    'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统
    },
    }
    }
    #utils/logger

    import logging
    # log=logging.getLogger('名字') # 跟配置文件中loggers日志对象下的名字对应
    log=logging.getLogger('django')


    # 以后使用,导入直接用
    from luffyapi.utils.logger import log
    log.info('xxxxxx') # 不要写print
    ```


    ## 2 跨域问题及解决

    ```python
    # xss:跨站脚本攻击,cors:跨域资源共享,csrf:跨站请求伪造

    # 1 同源策略:请求的url地址,必须与浏览器上的url地址处于同域上,也就是域名,端口,协议相同.
    # 2 CORS:跨域资源共享,允许不同的域来我的服务器拿数据
    # 3 CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)
    只要同时满足以下两大条件,就属于简单请求
    (1) 请求方法是以下三种方法之一:
    HEAD
    GET
    POST
    (2)HTTP的头信息不超出以下几种字段:
    Accept
    Accept-Language
    Content-Language
    Last-Event-ID
    Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

    #如果发送post请求,数据格式是json---》非简单请求,非简单请求发两次,一次OPTIONS请求,一次真正的请求
    # 4 后端处理,开启cors,跨域资源共享(在中间中写)
    class MyMiddle(MiddlewareMixin):
    def process_response(self, request, response):
    response['Access-Control-Allow-Origin'] = '*'
    if request.method == "OPTIONS":
    # 可以加*
    response["Access-Control-Allow-Headers"] = "Content-Type"
    response["Access-Control-Allow-Headers"] = "authorization"

    return response
    #5 在setting的中间件中配置


    #6使用第三方,django-cors-headers
    -pip install django-cors-headers
    -注册app:'corsheaders',
    -配置中间件:corsheaders.middleware.CorsMiddleware
    -setting中配置:
    CORS_ORIGIN_ALLOW_ALL = True
    CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
    )
    CORS_ALLOW_HEADERS = (
    'authorization',
    'content-type',
    )


    ```


    ## 3 前后台打通

    ```python
    #1 前台可以发送ajax的请求,axios
    #2 cnpm install axios
    #3 配置在main.js中
    import axios from 'axios' //导入安装的axios
    //相当于把axios这个对象放到了vue对象中,以后用 vue对象.$axios
    Vue.prototype.$axios = axios;


    #4 使用(某个函数中)
    this.$axios.get('http://127.0.0.1:8000/home/home/'). 向某个地址发送get请求
    then(function (response) { 如果请求成功,返回的数据再response中
    console.log(response)
    }).catch(function (error) {
    console.log(error)
    })

    #5 es6的箭头函数
    function (response) { console.log(response)}
    response=>{ console.log(response)}
    ```



    ## 4 xadmin后台管理


    ```python
    # 1 安装 pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
    # 2 在app中注册
    # xadmin主体模块
    'xadmin',
    # 渲染表格模块
    'crispy_forms',
    # 为模型通过版本控制,可以回滚数据
    'reversion',

    # 3 数据迁移
    python manage.py makemigrations
    python manage.py migrate
    # 4 主路由替换掉admin:主urls.py
    # xadmin的依赖
    import xadmin
    xadmin.autodiscover()
    # xversion模块自动注册需要版本控制的 Model
    from xadmin.plugins import xversion
    xversion.register_models()

    urlpatterns = [
    # ...
    path(r'xadmin/', xadmin.site.urls),
    ]
    # 5 # 在项目根目录下的终端
    python manage.py createsuperuser
    # 账号密码设置:admin | Admin123

    ```
  • 相关阅读:
    Codeforces 868A Bark to Unlock
    poj 3744 Scout (Another) YYF I
    Codeforces 526F Pudding Monsters
    Codeforces 789D Weird journey
    Codeforces 827E Rusty String
    Codeforces 841D Leha and another game about graph
    bzoj 3560 DZY Loves Math V
    Codeforces 833A The Meaningless Game
    Codeforces 839D Winter is here
    Codeforces 839C Journey
  • 原文地址:https://www.cnblogs.com/0B0S/p/13618035.html
Copyright © 2011-2022 走看看