2024年4月22日 星期一

在Django中設定和存取Session的內容

參考資料:Python架站特訓班django最強實戰
1.在CookieSession/CookieSession/urls.py,增加set_session和get_session兩個路徑對應到函式

 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
"""
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, set_session, get_session

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('set_cookie/<str:key>/<str:value>/', set_cookie),
    path('get_cookie/<str:key>/', get_cookie),
    path('set_session/<str:key>/<str:value>/', set_session),
    path('get_session/<str:key>/', get_session),
]

2.在CookieSession/CookieSessionApp/views.py,增加set_session和get_session兩個函式

 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
30
31
32
33
34
35
36
37
38
39
40
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

def set_session(request,key=None,value=None):
	response = HttpResponse('Session 儲存完畢!')
	request.session[key]=value
	return response
	
def get_session(request,key=None):
	if key in request.session:
		return HttpResponse('%s : %s' %(key,request.session[key]))
	else:
		return HttpResponse('Session 不存在!')	

3.測試
3.1 http://127.0.0.1:8000/set_session/name/虎尾鎮/

3.2 http://127.0.0.1:8000/get_session/name/



沒有留言:

張貼留言