django 安全

from django.shortcuts import HttpResponse
import demjson
import functools


# 定义装饰器
def api(func):
    @functools.wraps(func)
    def deal_with(*args, **kwargs):
        response_data = demjson.encode(func(*args, **kwargs))
        response = HttpResponse(response_data, content_type='application/json')
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "*"
        return response
    return deal_with


@api
def api_safe(request):
    time_stamp = time.time()
    auth_key = request.META.get("HTTP_KEY")
    if not auth_key:
        return {'msg': 'you are not client'}
    # auth_key = 32位字符串|时间戳|其它字符
    client_md5_str, client_time = auth_key.split("|")
    client_time = float(client_time)
    if client_time + 100 < time_stamp:
        return {'msg': 'time out'}
    server_md5_str = md5("{}|{}".format(key, client_time))
    if server_md5_str != client_md5_str:
        return {'msg': 'key not right'}
    if client_md5_str in visited_api:
        return {'msg': 'you have visited'}
    visited_api[client_md5_str] = client_md5_str
    return {'msg': 'hello world'}

猜你喜欢

转载自blog.csdn.net/weixin_42336579/article/details/81147087
今日推荐