装饰器api
import hashlib import time from django.http import HttpResponse key="qwrwertyuiop" visited_key={ #'key':time } def api_auth(func): def inner(request,*args,**kwargs): server_float_ctime = time.time() auth_header_val = request.META.get("HTTP_AUTH_API") client_md5_str, client_ctime = auth_header_val.split("|", maxsplit=1) client_float_ctime = float(client_ctime) # 第一关时间 if (client_float_ctime + 10) < server_float_ctime: return HttpResponse("时间太久了") # 第二关加密 server_md5_str = md5("%s|%s" % (key, client_ctime,)) if client_md5_str != server_md5_str: return HttpResponse("休想") # 第三关 if visited_key.get(client_md5_str): return HttpResponse("you are late") visited_key[client_md5_str] = client_float_ctime return func(request,*args,**kwargs) return inner def md5(arg): hs=hashlib.md5() #由于在python3中在update用的是字节类型所以需要把字符串变成字节 hs.update(arg.encode("utf8")) return hs.hexdigest() @api_auth def test(request): # server_float_ctime = time.time() # auth_header_val=request.META.get("HTTP_AUTH_API") # client_md5_str,client_ctime=auth_header_val.split("|",maxsplit=1) # client_float_ctime=float(client_ctime) # #第一关时间 # if (client_float_ctime+10) < server_float_ctime: # return HttpResponse("时间太久了") # # 第二关加密 # server_md5_str = md5("%s|%s" %(key,client_ctime,)) # # if client_md5_str != server_md5_str: # return HttpResponse("休想") # # #第三关 # if visited_key.get(client_md5_str): # return HttpResponse("you are late") # visited_key[client_md5_str]=client_float_ctime return HttpResponse("正常用户")