AI智能
改变未来

Django自定义middleware

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\',]
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Django自定义middleware