视图函数装饰器通用格式
def deco(view_func):
def inner(*args, **kwargs):
print('111')
res = view_func(*args, **kwargs)
print(222)
return res
return inner
# Create your views here.
@deco
def regist(request):
print('regist', request.META.get("REMOTE_ADDR"))
return render(request, "regist.html")
例-黑名单拦截装饰器
black_list = ["127.0.0.1", "127.1.1.1"]
# 阻止黑名单装饰器
def stop_black_list(func):
def inner(request, *args, **kwargs):
# 获取访问者的ip
remote_addr = request.META.get("REMOTE_ADDR")
# 黑名单验证
if remote_addr in black_list:
return HttpResponse("22非法用户,禁止访问")
# 主程序执行
res = func(request, *args, **kwargs)
return res
return inner