簡體   English   中英

Cookie未顯示在Chrome開發者工具(Django Python)中

[英]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_visitvisits Cookie的顯示方式。 這些是我運行代碼后在開發人員工具上看不到的內容。 下圖說明了我在網絡瀏覽器中看到的內容: 在此處輸入圖片說明

有人可以向我解釋為什么即使我的代碼在views.py中將它們顯式設置后,我仍然看不到這兩個cookie嗎?

您檢查last_visit cookie是否已經存在,並且僅在存在時更新它。 如果沒有,該怎么辦? 您是第一次在哪里創建它?

我懷疑出現縮進錯誤:最后的else塊應該在左側一級,因此如注釋所述,如果last_visit不存在,則運行該塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM