我的网站有很多视图,我想检查每个视图中的 cookie,如果没有,请保存它们。但网站有很多意见。
如何对所有视图只执行一次?
您可以编写自定义中间件来实现您的目标,因为您有很多视图,当然您不能更新每个视图。自定义中间件将是这样的:
class MyCookieProcessingMiddleware(object):
# your desired cookie will be available in every django view
def process_request(self, request):
# will only add cookie if request does not have it already
if not request.COOKIES.get('your_desired_cookie'):
request.COOKIES['set_your_desired_cookie'] = 'value_for_desired_cookie'
# your desired cookie will be available in every HttpResponse parser like browser but not in django view
def process_response(self, request, response):
if not request.COOKIES.get('your_desired_cookie'):
response.set_cookie('set_your_desired_cookie', 'value_for_desired_cookie')
return response
在您的settings.py
文件中,只需将路径添加到您的自定义中间件,如下所示:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'MyProject.myapp.mymodule.MyCookieProcessingMiddleware', # path to custom class
)
中间件的顺序很重要,你的属于 SessionMiddleware 之后。
我的理解是,您想设置一次 cookie,然后想在任何视图中检查它的值。如果这是您的问题,那么您可以在这样的视图中保存一次 cookie:
from project.settings import IS_COOKIE_SET # Set Global value for cookie
response = render_to_response("your-template.html")
if !IS_COOKIE_SET:
response.set_cookie('key', 'value')
return response
else:
return response
您可以在任何其他视图中检查 cookie 的值,如下所示:
request.COOKIES.get('key', None) # Return None If cookie not exists