我的网站有很多视图,我想检查每个视图中的cookie,当它没有时 - 保存它们。但网站有很多观点。
如何只对所有观看一次?
答案 0 :(得分:7)
您可以编写自定义中间件来实现目标,因为您有很多视图,当然您无法更新每个视图。自定义中间件将是这样的:
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。
答案 1 :(得分:1)
我的理解是,您想要设置一次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