ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python Django 12 - session(redirec 방법)
    Python Django 2022. 10. 23. 14:35

     

    urls.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),
    ]

    page가 3개이므로 3개 작성

     

     

    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"가 없는 경우
    
    
    
    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['massage'] = "운영체제를 선택하지 않았군"
            
        # del request.session["f_os"] # 특정 세션 삭제
        request.session.set_expiry(5) # 5초 후 세션 삭제
        # set_expiry(0) 브라우저가 닫힐 때 세션이 해제된다.
        
        return render(request, 'show.html', dict_context)

    setOsFunc함수에서 get방식을 가져오지 못했으면 selectos.html로 이동시키고 get방식으로 가져왔으면 그 값을 세션에 담아 redirec로 show.html로 이동시키는 것이다. 그러므로 처음 들어갔을 때는 무조건 selectos.html로 이동된다.

    get 방식의 값이 아무것도 없기때문이다.

    forward방식은 urls.py에서 다른 path로 이동을 못하므로 redirec를 이용해서 만든다.

    한 페이지 안에서 이동을 두번 해야되기에 redirec 방식을 이용했다.

    showOsFunc에 도착한 값을 세션이 있으면 불러내고 없으면 None을 호출한다. 5초동안 유효하게 설정해두었다.

     

     

    main.html

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

     

     

    selectos.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>session test</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>

    get방식으로 값을 가져가며 그 값을 show.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>

    세션 결과를 나타낸다.

     

     

     

    댓글

Designed by Tistory.