[英]How to extract href attributes that show up on chrome's developer tools, but not on BeautifulSoup's output
[英]Cookie does not show up in Chrome Developer Tools (Django Python)
背景知识:在过去的几周里,我一直在致力于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吗?
您检查last_visit cookie是否已经存在,并且仅在存在时更新它。 如果没有,该怎么办? 您是第一次在哪里创建它?
我怀疑出现缩进错误:最后的else
块应该在左侧一级,因此如注释所述,如果last_visit不存在,则运行该块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.