【问题标题】:Cookie does not show up in Chrome Developer Tools (Django Python)Cookie 未显示在 Chrome 开发人员工具 (Django Python) 中
【发布时间】: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_visitvisits cookie 的显示方式。这些是我运行代码后在开发人员工具上看不到的。下图说明了我在网络浏览器上看到的内容:

有人可以向我解释为什么即使我的代码在views.py 中明确设置了这两个cookie,我还是看不到它们?

【问题讨论】:

    标签: python django cookies


    【解决方案1】:

    您检查 last_visit cookie 是否已经存在,如果存在则仅更新它。如果没有怎么办?您第一次在哪里创建它?

    我怀疑有缩进错误:最后一个 else 块应该在左边一层,所以如果 last_visit 不存在,它就会运行,如注释所述。

    【讨论】:

    • 我设置了最后一个 else 块,我得到了 last_visit 显示。但是访问仍然没有出现。我认为那是因为计数器每天只增加一次??
    猜你喜欢
    • 2015-05-24
    • 2012-07-02
    • 2019-08-25
    • 2017-07-30
    • 2023-03-18
    • 2020-10-08
    • 2018-02-21
    • 2020-11-05
    • 2020-09-06
    相关资源
    最近更新 更多