Python + Django项目常用装饰器及自定义函数

1.自定义返回请求值的函数:

def render_json(data, status=200):
    return HttpResponse(json.dumps(data), content_type="text/json", status=status)
 
def render_json_error(message, status=400):
    return render_json(message, status)
 
def response_401(msg="Unauthorized"):
    return HttpResponse(msg + "\n", status=401)
 
def response_400(msg="Bad Request"):
    return HttpResponse(msg + "\n", status=400)
 
def response_403(msg="Forbidden"):
    return HttpResponse(msg + "\n", status=403)
 
def response_404(msg="Not Found"):
    return HttpResponse(msg + "\n", status=404)
 
def response_200(msg="OK"):
    return HttpResponse(msg + "\n", status=200)

2.自定义格式化时间的函数:

def format_time(date):
    return date.strftime("%Y-%m-%d %H:%M")

3.操作日志装饰器:

def log_action(action, method="ALL"):
    def log_action_wrapper(func):
        @wraps(func)
        def _wrapper(request, *args, **kwargs):
            if method == "ALL" or request.method == method:
                user = request.user
                ActionLog.add(action, user.name)
            return func(request, *args, **kwargs)
        return _wrapper
    return log_action_wrapper

4.权限需求装饰器:

def admin_required(func):
    @wraps(func)
    def _wrapper(request, *args, **kwargs):
        role = request.session['role']
        if role == USER_ROLE[0]:
            return render_json({'success': False, 'message': _('Sorry, you have no permission')})
        else:
            return func(request, *args, **kwargs)
    return _wrapper

5.要求登录装饰器:

def login_require(func):
    @wraps(func)
    def _wrapper(request, *args, **kwargs):
        if 'user_id' not in request.session:
            request.user = None
            return render(request, 'portal/login/login.html')
        else:
            return func(request, *args, **kwargs)
    return _wrapper

6.导航栏选中变亮装饰器:

def active_navs(*nav_args):
    def active_navs_wrapper(func):
        @wraps(func)
        def _wrapper(request, *args, **kwargs):
            request.actives = nav_args
            return func(request, *args, **kwargs)
        return _wrapper
    return active_navs_wrapper