import uuidUSER_KEY = \'uid\'THE_YEARS = 60 * 60 * 24 * 365 * 10class UserIDMiddleware:def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):uid = self.generate_uid(request)request.uid = uidresponse = self.get_response(request)response.set_cookie(USER_KEY, uid, max_age=THE_YEARS, httponly=True)return responsedef generate_uid(self, request):try:uid = request.COOKIES[USER_KEY]except KeyError:uid = uuid.uuid4().hexreturn uid
url中加入:
MIDDLEWARE = [\'blog.middleware.user_id.UserIDMiddleware\',]