Django

django3 - session

bono.html 2022. 10. 17. 15:40

 

url.py

from django.contrib import admin
from django.urls import path
from sessionapp import views

urlpatterns = [
    path("admin/", admin.site.urls),
    
    path('', views.mainFunc),
    path('setos', views.setOsFunc),
    path('showos', views.showOsFunc),
]

 

views.py

from django.shortcuts import render
from django.http.response import HttpResponseRedirect


# Create your views here.
# 아래 모든 방식을 알아둬야 한다.

def mainFunc(request): 
    return render(request,'main.html')
    
def setOsFunc(request):
    if "favorite_os" in request.GET:
        #print(request.GET.get("favorite_os")) 아래 코드와 같은 의미이다.
        print(request.GET["favorite_os"])
        
        #'f_os' 라는 키로 세션을 생성한다.
        request.session["f_os"]=request.GET["favorite_os"]
        # return render() 형식은 forwarding 이기 때문에 클라이언트를 통한 요청 불가
        # 다시 말해, 메인 urls.py 를 만날 수 없다.
        # 하나의 클라이언트마다 별도로 하나의 세션에 각각 담았다.
        
        # forwarding 말고 redirect 방식을 사용한다면 가능함
        return HttpResponseRedirect('/showos')
    else:
        return render(request,'selectos.html') # 요청값에 'favorite_os'이 없는 경우 selectos를 만나게 한다
        
                
def showOsFunc(request):
    #print('여기까지 도착')
    dict_context={}
    
    if "f_os" in request.session: #세션 값 중에 "f_os"가 있으면 처리
        print('유효 기간 : ', request.session.get_expiry_age())
        dict_context['sel_os']=request.session["f_os"]
        dict_context['message']="그대가 선택한 운영체제는 %s"%request.session["f_os"]
    else:
        dict_context['sel_os']=None
        dict_context['message']="운영체제를 선택하지 않았군요"
    
    #del request.session["f_os"] #특정 세션 삭제
    request.session.set_expiry(5) #5초 후 세션 삭제
    # set_expiry(0) #브라우저가 닫힐 때 세션이 해제됨
    
    return render(request, 'show.html', dict_context)

 

 

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
메인<p/>
메뉴1 메뉴2 <a href="setos">운영체제 선택</a> 묻고답하기
</body>
</html>

 

 

selectos.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>세션 이해</h2>
<p>운영체제(os) 선택</p>
<a href="setos?favorite_os=window">윈도우</a>
<a href="setos?favorite_os=macos">맥os</a>
<a href="setos?favorite_os=linux">리눅스</a>
</body>
</html>

 

 

show.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
세션 결과 : {{sel_os}} <br>
메세지 : {{message}} <br>
세션값 직접 보기 : {{request.session.f_os}}<br>
현재 사용자에게 할당된 세션 id : {{request.session.session_key}}
<hr>
<a href="setos">os 선택</a><br>
<a href="/">메인</a><br>
</body>
</html>