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

友情提醒:本文最后更新于 2751 天前,文中所描述的信息可能已发生改变,请谨慎使用。
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 record_operate(action=""):
    """
    操作记录装饰器, 用于记录用户操作的装饰器
    """
    def decorator(view_func):
        @wraps(view_func)
        def _operate_record(request, *args, **kwargs):
            if request.method == "POST":
                data = json.dumps(request.POST).decode("raw_unicode_escape")
                try:
                    RecordOperate.objects.create(
                        hera_user_id=1,
                        action=action,
                        data=data,
                    )
                except Exception as ex:
                    SysLogger.exception(ex, request)
            return view_func(request, *args, **kwargs)
        return _operate_record
    return decorator
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
7. 计算函数执行时间
def time_use():
    @wraps(view_func)
    def _time_use(*args, **kwargs):
        start = time.time()
        return view_func(*args, **kwargs)
        end = time.time()
        print(end - start)
    return _time_use

上一篇:Django项目常用验证及写法

下一篇:Ubuntu修改gem源