參考資料:Python架站特訓班django最強實戰
上一篇文章:在Django中使用Cookies來計算今天瀏覽次數
想從剛從建立專案開始,務必參考上一篇文章。
1.在CookieSession/CookieSession/urls.py,增加set_cookie和get_cookie兩個路徑對應到函式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | """ URL configuration for CookieSession project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from CookieSessionApp.views import index, set_cookie, get_cookie urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('set_cookie/<str:key>/<str:value>/', set_cookie), path('get_cookie/<str:key>/', get_cookie), ] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | from django.shortcuts import render
from django.http import HttpResponse
import datetime
# Create your views here.
def set_cookie(request,key=None,value=None):
response = HttpResponse('Cookie 儲存完畢!')
response.set_cookie(key,value.encode('utf-8').decode('latin-1'))
return response
def get_cookie(request,key=None):
if key in request.COOKIES:
return HttpResponse('%s : %s' %(key,request.COOKIES[key].encode('latin-1').decode('utf-8')))
else:
return HttpResponse('Cookie 不存在!')
def index(request):
if "counter" in request.COOKIES:
counter=int(request.COOKIES["counter"])
counter+=1
else:
counter=1
response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))
tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie("counter",counter,expires=expires)
return response
|
3.測試
3.1 http://127.0.0.1:8000/set_cookie/name/虎尾鎮/
沒有留言:
張貼留言