【发布时间】:2015-01-12 04:20:03
【问题描述】:
一些背景知识:过去几周我一直在研究 tangowithdjango.com 教程,并且一直在思考如何让 cookie 显示在 Chrome 中的“开发者工具”小部件上浏览器。我在 Mac OS X Mountain Lion 上运行 Python 2.7.5 和 Django 1.5.4。
现在解决手头的问题:我正在使用 Django 作为教程的一部分构建网页。我坚持的当前练习需要我对 cookie 做一些工作。我使用教程中提供给我的代码来设置站点访问计数器,当用户访问我的站点时,该计数器每天递增一次。这是我在 index.html 页面(主页)的views.py 文件中的代码:
def index(request):
context = RequestContext(request)
category_list = Category.objects.all()
top_five_cats = Category.objects.order_by('-views')[:5]
if enc_bool == False:
EncodeUrl(category_list, top_five_cats)
context_dict = {'categories': category_list, 'top_five_cats': top_five_cats}
# Obtain our Response object early so we can add cookie information.
response = render_to_response('rango/index.html', context_dict, context)
#-----IMPORTANT CODE STARTS HERE:-----
# Get the number of visits to the site.
# We use the COOKIES.get() function to obtain the visits cookie.
# If the cookie exists, the value returned is casted to an integer.
# If the cookie doesn't exist, we default to zero and cast that.
visits = int(request.COOKIES.get('visits', '0'))
print "visits: ",visits
# Does the cookie last_visit exist?
if 'last_visit' in request.COOKIES:
# Yes it does! Get the cookie's value.
last_visit = request.COOKIES['last_visit']
print "last visit: ", last_visit
print
# Cast the value to a Python date/time object.
last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
# If it's been more than a day since the last visit...
if (datetime.now() - last_visit_time).days > 0:
# ...reassign the value of the cookie to +1 of what it was before...
response.set_cookie('visits',visits+1)
# ...and update the last visit cookie, too.
response.set_cookie('last_visit', datetime.now())
else:
# Cookie last_visit doesn't exist, so create it to the current date/time.
response.set_cookie('last_visit', datetime.now())
return response
#-----IMPORTANT CODE ENDS-----
注意:请从评论“重要代码从这里开始”开始阅读
我应该看到如下:
注意last_visit 和visits cookie 的显示方式。这些是我运行代码后在开发人员工具上看不到的。下图说明了我在网络浏览器上看到的内容:
有人可以向我解释为什么即使我的代码在views.py 中明确设置了这两个cookie,我还是看不到它们?
【问题讨论】: