open:django-세션-사용하기

Django 세션 사용하기 ((How to use sessions))

원문 : https://docs.djangoproject.com/en/1.11/topics/http/sessions/

Django는 익명 세션을 완벽하게 지원합니다. 세션 프레임워크를 사용하면 사이트 방문자별로 임의의 데이터를 저장하고 검색 할 수 있습니다. 서버 측에 데이터를 저장하고 쿠키 송수신을 추상화합니다. 쿠키에는 세션 ID가 들어 있지만 데이터 자체는 아닙니다. (쿠키 기반 백엔드를 사용하지 않는 한)
1)

2)

세션은 미들웨어를 통해 구현됩니다.3)

세션 기능을 사용하려면 다음을 수행하십시오.
4)

  • `MIDDLEWARE` 설정하고 포함되어 있는지 확인하십시오.
    5)
  • django.contrib.sessions.middleware.SessionMiddleware에 의해 만들어진 settings.py 기본 설정 django-admin startprojectSessionMiddleware를 활성화했습니다.
    6)

세션을 사용하고 싶지 않은 경우에는 `MIDDLEWARE`에서 'SessionMiddlewareline '을 삭제하고 `INSTALLED_APPS`에서는 'django.contrib.sessions'를 삭제할 수 있습니다. 약간의 오버 헤드를 줄일 수 있습니다.
7)

8)

기본적으로 Django는 데이터베이스에 세션을 저장합니다 (모델 django.contrib.sessions.models.Session ). 이 설정은 편리하지만 일부 설정에서는 세션 데이터를 다른 곳에 저장하는 것이 더 빠르기 때문에 파일 시스템이나 캐시에 세션 데이터를 저장하도록 Django를 구성 할 수 있습니다.
9)

10)

데이터베이스 기반 세션을 사용하려면 django.contrib.sessions`INSTALLED_APPS`에 추가해야합니다.
11)

설치를 구성한 후에는manage.pymigrate를 실행하여 세션 데이터를 저장하는 단일 데이터베이스 테이블을 설치하십시오.
12)

13)

성능 향상을 위해 캐시 기반 세션 백엔드를 사용할 수 있습니다.
14)

Django의 캐시 시스템을 사용하여 세션 데이터를 저장하려면 먼저 캐시를 구성했는지 확인해야합니다. 자세한 내용은 cache documentation를 참조하십시오.
15)

Memcached 캐시 백엔드를 사용하는 경우에만 캐시 기반 세션을 사용해야합니다. 로컬 메모리 캐시 백엔드는 데이터를 충분히 길게 유지하지 않으며, 파일 또는 데이터베이스 캐시 백엔드를 통해 모든 것을 보내는 대신 직접 파일 또는 데이터베이스 세션을 사용하는 것이 빠릅니다. 또한 로컬 메모리 캐시 백엔드는 다중 프로세스 안전이 아니므로 프로덕션 환경에 적합하지 않을 수 있습니다.
16)

CACHES에 정의 된 캐시가 여러 개인 경우 Django는 기본 캐시를 사용합니다. 다른 캐시를 사용하려면 해당 캐시의 이름을 `SESSION_CACHE_ALIAS`로 설정하십시오.
17)

캐시가 구성되면 캐시에 데이터를 저장하는 방법에 대해 두 가지 선택 사항이 있습니다.
18)

  • `SESSION_ENGINE`
    django.contrib.sessions.backends.cache을 설정합니다. 간단한 캐싱 세션 저장소. 세션 데이터는 캐시에 직접 저장됩니다. 그러나 세션 데이터가 지속되지 않을 수 있습니다. 캐시가 가득 차거나 캐시 서버가 다시 시작되면 캐시 된 데이터가 제거 될 수 있습니다.
    19)
  • 지속적이고 캐시 된 데이터의 경우 `SESSION_ENGINE`
    django.contrib.sessions.backends.cached_db을 설정합니다. 이것은 연속 기입 캐시를 사용합니다. 캐시에 대한 모든 쓰기도 데이터베이스에 기록됩니다. 세션 읽기는 데이터가 캐시에없는 경우에만 데이터베이스를 사용합니다.
    20)

두 세션 저장소는 모두 빠르지 만 지속성을 무시하기 때문에 단순한 캐시가 빠릅니다. 대부분의 경우,cached_db 백엔드는 충분히 빠르지 만 성능의 마지막 비트가 필요하고 때때로 세션 데이터를 소멸 시키려고한다면 cache 백엔드가 당신을위한 것입니다.
21)

cached_db 세션 백엔드를 사용한다면, 데이터베이스 기반 세션 사용하기에 대한 설정 지시 사항을 따라야합니다.
22)

23)

파일 기반 세션을 사용하려면 `SESSION_ENGINE` 설정에 django.contrib.sessions.backends.file을 설정합니다.
24)

`SESSION_FILE_PATH` 설정을 원할 수도 있습니다 (기본값은 tempfile.gettempdir (), 가장 가능성있는 /tmp)를 사용하여 Django가 세션 파일을 저장하는 위치를 제어 할 수 있습니다. 웹서버의 위치를 읽고 쓸 수있는 권한이 있는지 확인하십시오.
25)

26)

쿠키 기반 세션을 사용하려면 `SESSION_ENGINE`django.contrib.sessions.backends.signed_cookies을 설정하십시오. 세션 데이터는 Django의 암호화 서명`SECRET_KEY` 도구를 사용하여 저장됩니다.
27)

Note

자바 스크립트에서 저장된 데이터에 액세스하지 못하도록 하려면 `SESSION_COOKIE_HTTPONLY` 설정을 True로 설정하는 것이 좋습니다.
28)

Warning

SECRET_KEY가 비밀로 유지되지 않고 `PickleSerializer`를 사용하고 있다면, 이로 인해 임의의 원격 코드 실행이 발생할 수 있습니다.
29)

SECRET_KEY를 소유 한 공격자는 사이트가 신뢰할 수 있는 위조된 세션 데이터 생성 뿐만 아니라. pickle을 사용하여 데이터가 직렬화되기 때문에 원격으로 임의의 코드를 실행할수 있습니다.
30)

쿠키 기반 세션을 사용하는 경우 원격으로 액세스 할 수 있는 시스템의 경우 항상 비밀키가 항상 비밀로 유지되어야 합니다.
31)

세션 데이터는 서명되었지만 암호화되지 않았습니다.
32)

쿠키 백엔드를 사용할 때 클라이언트가 세션 데이터를 읽을 수 있습니다.
33)

MAC(Message Authentication Code)는 클라이언트가 변경 한 데이터를 보호하기 위해 사용되므로 세션 데이터가 변조 될 때 무효화됩니다. 쿠키를 저장하는 클라이언트 (예: 사용자의 브라우저)가 모든 세션 쿠키를 저장하고 데이터를 삭제할 수없는 경우에도 동일한 무효화가 발생합니다. Django가 데이터를 압축하더라도 cookie 당 4096 bytes 제한을 초과 할 수 있습니다.
34)

최신에 대한 보장을 못함
35)

또한 MAC가 데이터의 진위성을 보장 할 수 있지만 (데이터가 사이트 및 다른 사람이 생성하지 않음) 데이터의 무결성을 보장 할 수 있지만 (데이터가 모두 있고 올바른), 신선도를 보장합니다. 즉, 클라이언트에 마지막으로 보낸 것을 다시 보냈습니다. 즉, 세션 데이터를 일부 사용하는 경우 쿠키 백엔드가 replay attacks까지 열 수 있습니다. 사용자가 로그 아웃 할 때 각 세션의 서버 측 기록을 유지하고 무효화하는 다른 세션 백엔드와 달리, 사용자가 로그 아웃 할 때 쿠키 기반 세션은 무효화되지 않습니다. 따라서 공격자가 사용자의 쿠키를 훔칠 경우 해당 쿠키를 사용하여 사용자가 로그 아웃하더라도 해당 사용자로 로그인 할 수 있습니다. 쿠키가 `SESSION_COOKIE_AGE`보다 오래된 경우 쿠키는 '부실함(stale)'으로 만 감지됩니다.
36)

성능
37)

마지막으로, 쿠키의 크기는 사이트 속도에 영향을 줄 수 있습니다.
38)

39)

SessionMiddleware가 활성화되면 각각의 `HttpRequest` 객체 - Django 뷰의 첫 번째 인수 함수 - 사전과 같은 객체인 '세션'속성을 갖습니다.
40)

당신은 당신의 관점에서 그것을 읽고 request.session에 쓸 수 있습니다. 여러 번 편집 할 수 있습니다.
41)

class backends.base.SessionBase

이것은 모든 세션 객체의 기본 클래스입니다. 다음과 같은 표준 사전 방법이 있습니다.
42)

__getitem__(key)
snippet.python
Example: fav_color=request.session['fav_color']
__setitem__(key, value)
snippet.python
Example: request.session['fav_color']='blue'
__delitem__(key)
snippet.python
Example: del request.session['fav_color']. 

주어진 키가 이미 세션에없는 경우 이것은 KeyError를 발생시킵니다.
43)

__contains__(key)
snippet.python
Example: 'fav_color' in request.session
get(key, default=None)
snippet.python
Example: fav_color=request.session.get('fav_color','red')
pop(key, default=__not_given)
snippet.python
Example: fav_color=request.session.pop('fav_color','blue')
keys()
items()
setdefault()
clear()

또한 다음과 같은 방법이 있습니다.44)

flush()

세션에서 현재 세션 데이터를 삭제하고 세션 쿠키를 삭제합니다. 이것은 사용자의 브라우저에서 이전 세션 데이터에 다시 액세스 할 수 없도록 하려는 경우에 사용됩니다 (예 : `django.contrib.auth.logout()` 함수를 호출합니다.
45)

테스트 쿠키를 설정하여 사용자 브라우저가 쿠키를 지원하는지 여부를 결정합니다. 쿠키가 작동하는 방식 때문에 사용자가 다음 페이지 요청을 할 때까지이를 테스트 할 수 없습니다. 자세한 내용은 아래의 테스트 쿠키 설정을 참조하십시오.
46)

사용자 브라우저가 테스트 쿠키를 수락했는지 여부에 따라 True또는False를 반환합니다. 쿠키가 작동하는 방식 때문에 이전의 별도의 페이지 요청에서 set_test_cookie ()를 호출해야합니다. 자세한 내용은 아래의 테스트 쿠키 설정을 참조하십시오.
47)

테스트 쿠키를 삭제합니다. 이것을 사용하여 자신을 정리하십시오.
48)

set_expiry(value)

세션의 만기 시간을 설정합니다. 다양한 값을 전달할 수 있습니다.
49)

  • 만약 value가 정수이면 몇 초 동안 활동하지 않으면 세션이 만료됩니다. 예를 들어, 호출
    request.session.set_expiry (300)를 호출하면 5분 안에 세션이 만료됩니다.
    50)
  • valuedatetime 또는timedelta 객체라면, 세션은 그 특정 날짜/시간에 만료 될 것입니다. PickleSerializer를 사용하는 경우 datetimetimedelta 값은 직렬화 가능합니다.
    51)
  • value0이면 사용자의 웹 브라우저가 닫힐 때 세션 쿠키가 만료됩니다.
    52)
  • valueNone이면, 세션은 전역 세션 만료 정책을 사용하는 것으로 되돌아갑니다.
    53)

세션 읽기는 만료 목적의 활동으로 간주되지 않습니다. 세션 만료는 세션이 마지막으로 수정 된 시간부터 계산됩니다.
54)

get_expiry_age()

이 세션이 만료 할 때까지의 초 수를 반환합니다. 사용자 정의 만료가없는 세션 (또는 브라우저 닫기에서 만료되도록 설정 한 세션)의 경우이 값은 `SESSION_COOKIE_AGE`와 같습니다.
55)

이 함수는 두 개의 선택적 키워드 인수를 허용합니다.
56)

  • modification : 세션의 마지막 수정으로서 `datetime` 객체입니다. 기본값은 현재 시간입니다.
    57)
  • expiry : 세션의 만기 정보 `datetime` 객체,
    `int` (초 단위) 또는
    'None'. 기본값은 `set_expiry()`에 의해 세션에 저장된 값입니다. 하나가 있거나 'None'.
    58)
get_expiry_date()

이 세션이 기한 마감일을 반환합니다. 사용자 정의 만료가없는 세션 (또는 브라우저 닫기에서 만료되도록 설정 한 세션)의 경우이 값은 `SESSION_COOKIE_AGE` 지금부터 날짜 초와 같습니다.
59)

이 함수는 get_expiry_age()와 동일한 키워드 인수를 받습니다
60)

get_expire_at_browser_close()

사용자의 웹 브라우저가 닫힐 때 세션 쿠키가 만료되는지 여부에 따라 True 또는 False를 반환합니다.
61)

clear_expired()

만료 된 세션을 세션 저장소에서 제거합니다. 이 클래스 메소드는 `clearsessions`에 의해 호출됩니다.
62)

cycle_key()

현재 세션 데이터를 유지하면서 새 세션 키를 만듭니다. `django.contrib.auth.login ()`은 세션 고정에 대한 완화를 위해이 메소드를 호출합니다.
63)

64)

기본적으로 장고는 JSON을 사용하여 세션 데이터를 직렬화합니다. `SESSION_SERIALIZER` 설정을 사용하여 세션 직렬화 형식을 사용자 정의 할 수 있습니다.
65)

[자신의 시리얼 라이저 작성] (https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers)에 설명 된주의 사항이 있더라도 JSON 직렬화를 사용하는 것이 좋습니다. 특히 사용중인 경우 쿠키 백엔드.

특히 쿠키 백엔드를 사용중이라면 자신의 직렬화 작성에 설명 된주의 사항이 있더라도 JSON 직렬화를 사용하는 것이 좋습니다.
66)

예를 들어, `pickle`을 사용하여 세션 데이터를 직렬화하는 경우 공격 시나리오가 있습니다. 서명 된 쿠키 세션 백엔드`SECRET_KEY`)를 사용하는 경우, 공격자에 의해 알려지며 (Django의 고유 한 취약점으로 인해 누출 될 수 있음), 공격자는 문자열을 자신의 세션에 추가합니다. 이 세션은 unpickle 될 때 서버에서 임의의 코드를 실행합니다. 그렇게 하기 위한 기술은 간단하고 인터넷에서 쉽게 이용할 수 있습니다. 쿠키 세션 저장소가 변조를 방지하기 위해 쿠키에 저장된 데이터에 서명하지만 SECRET_KEY 누출이 즉시 원격 코드 실행 취약점으로 확대됩니다
67)

번들 직렬화

68)

class serializers.JSONSerializer

`django.core.signing`의 JSON 시리얼 라이저에 대한 래퍼. 기본 데이터 형식 만 serialize 할 수 있습니다.
69)

또한 JSON은 문자열 키만 지원하므로 request.session의 문자열이 아닌 키를 사용하면 예상대로 작동하지 않습니다.
70)

snippet.python
# initial assignment
request.session[0] = 'bar'
 
# subsequent requests following serialization & deserialization
# of session data 
request.session[0]     # KeyError
request.session['0']
'bar'

마찬가지로 JSON에서 인코딩 할 수 없는 데이터 (예: `UnicodeDecodeError`가 발생하는 '\ xd9'\와 같은 UTF8이 아닌 바이트)는 저장할 수 없습니다.
71)

JSON 직렬화의 제한 사항에 대한 자세한 내용은 자체 시리얼 작성 섹션을 참조하십시오.
72)

class serializers.PickleSerializer

임의의 파이썬 개체를 지원하지만 위에서 설명한대로 `SECRET_KEY`가 있으면 원격 코드 실행 취약점이 발생할 수 있습니다. )가 공격자에게 알려지게 됩니다.
73)

Write your own serializer

`PickleSerializer`와 달리 `JSONSerializer` 임의의 파이썬 데이터 유형을 처리 할 수 ​​없습니다. 종종 그렇듯이 편의성과 보안 성 사이에는 트레이드 오프가 있습니다.
74)

datetimeDecimal을 포함한 더 진보 된 데이터 타입을 JSON 지원 세션에 저장하고 싶다면, 커스텀 시리얼 라이저를 작성하거나 (request.session에 저장하기 전에 이러한 값을 JSON 직렬화 가능한 객체로 변환해야합니다). 이러한 값을 직렬화하는 것은 매우 간단합니다 (`DjangoJSONEncoder` 도움이 될 수 있습니다. 디코더는 안정적으로 당신이 넣는 것과 똑같은 것을 되 찾을 수 있습니다.
75)

예를 들어 datetime을 반환 할 위험이 있습니다. 실제로는 datetime과 같은 형식으로 된 문자열입니다.
76)

serializer 클래스는 세션 데이터의 사전을 직렬화 및 비 직렬화하는 두 가지 메소드, dumps(self, obj)loads(self, data)를 구현해야 합니다.
77)

  • request.session에서 사전 파이썬 문자열을 사전 키로 사용하십시오. 이는 어렵고 빠른 규칙보다 관례입니다.78)
  • 밑줄로 시작하는 세션 사전 키는 장고의 내부 용으로 예약되어 있습니다. 79)
  • request.session을 새로운 객체로 오버라이드하지 말고 그 속성에 접근하거나 설정하지 마라. 파이썬 사전처럼 사용하십시오.80)

이 간단한보기는 사용자가 주석을 게시 한 후 has_commented 변수를 True로 설정합니다. 사용자가 한 번 이상 주석을 게시 할 수 없습니다.
81)

snippet.python
def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

이 간단한보기는 사이트의 “회원”에 로그인합니다. 82)

snippet.python
def login(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        request.session['member_id'] = m.id
        return HttpResponse("You're logged in.")
    else:
        return HttpResponse("Your username and password didn't match.")

… 그리고 위의 login()에 따라 이 멤버를 로그 아웃합니다: 83)

snippet.python
def logout(request):
    try:
        del request.session['member_id']
    except KeyError:
        pass
    return HttpResponse("You're logged out.")

표준 `django.contrib.auth.logout ()` 함수는 실제로 약간의 기능 을합니다. 부주의한 데이터 유출을 막기 위해 request()`flush()` 메소드를 호출합니다. 세션. 우리는 완전한 logout() 구현이 아닌 세션 객체를 다루는 방법을 보여주기 위해이 예제를 사용하고 있습니다.
84)

85)

편의상 Django는 사용자의 브라우저가 쿠키를 허용하는지 테스트하는 쉬운 방법을 제공합니다.
86)

request.session`set_test_cookie()` 메소드를 호출하기만 하면됩니다. [test_cookie_worked ()] (https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked)를 호출하십시오. - 동일한 뷰 호출이 아닌 후속 뷰에서 호출합니다.
87)

쿠키가 작동하는 방식 때문에 set_test_cookie ()test_cookie_worked () 사이의 어색한 분리가 필요합니다. 쿠키를 설정하면 브라우저의 다음 요청이있을 때까지 브라우저가 쿠키를 허용했는지 여부를 실제로 알 수 없습니다.
88)

청소하기 위해 `delete_test_cookie()`를 사용하는 것이 좋습니다. 너 자신 후에. 테스트 쿠키가 작동하는지 확인한 후에이 작업을 수행하십시오.
89)

다음은 일반적인 사용 예입니다.
90)

snippet.python
from django.http import HttpResponse
from django.shortcuts import render
 
def login(request):
    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            return HttpResponse("You're logged in.")
        else:
            return HttpResponse("Please enable cookies and try again.")
    request.session.set_test_cookie()
    return render(request,'foo/login_form.html')

91)

Note

이 섹션의 예제는 django.contrib.sessions.backends.db 백엔드에서 직접 SessionStore 객체를 가져옵니다. 자신의 코드에서 `SESSION_ENGINE`에 의해 지정된 세션 엔진으로부터 SessionStore를 가져 오는 것을 고려해야합니다. 아래:
92)

snippet.python
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore

뷰 외부에서 세션 데이터를 조작하는 데 사용할 수있는 API는 다음과 같습니다.
93)

snippet.python
from django.contrib.sessions.backends.db import SessionStore
s = SessionStore()
# stored as seconds since epoch since datetimes are not serializable in JSON.
s['last_login'] = 1376587691
s.create()
s.session_key
'2b1189a188b44ad18c35e113ac6ceead'
s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
s['last_login']
1376587691

SessionStore.create()는 새로운 세션 (즉, 세션 저장소에서 로드되지 않고 session_key = None)을 생성하도록 설계되었습니다 .save()는 기존 세션을 저장하도록 설계되었습니다 (즉, 세션 저장소). 새 세션에서 save()를 호출해도 작동하지만 기존 세션과 충돌하는 session_key를 생성 할 가능성은 거의 없습니다. create()save()를 호출하고 사용되지 않는 session_key가 생성 될 때까지 반복합니다.
94)

django.contrib.sessions.backends.db 백엔드를 사용한다면, 각 세션은 정상적인 Django 모델 일뿐입니다. Session 모델은 django/contrib/sessions/models.py에 정의되어 있습니다. 정상적인 모델이기 때문에 일반적인 Django 데이터베이스 API를 사용하여 세션에 액세스 할 수 있습니다.
95)

snippet.python
from django.contrib.sessions.models import Session
s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)

`get_decoded()`를 다음과 같이 호출해야 합니다. 세션 사전을 얻으십시오. 이는 사전이 인코딩 된 형식으로 저장되기 때문에 필요합니다.
96)

snippet.python
s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
s.get_decoded()
{'user_id': 42}

97)

기본적으로 Django는 세션이 수정되었을 때, 즉 사전 값이 할당되거나 삭제 된 경우에만 세션 데이터베이스에 저장합니다.
98)

snippet.python
# Session is modified.
request.session['foo'] = 'bar'
 
# Session is modified.
del request.session['foo']
 
# Session is modified.
request.session['foo'] = {}
 
# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

위 예제의 마지막 경우에 세션 객체에 modified 속성을 설정하여 세션 객체가 명시 적으로 변경되었음을 세션 객체에 알릴 수 있습니다 :
99)

snippet.python
request.session.modified = True

이 기본 동작을 변경하려면 `SESSION_SAVE_EVERY_REQUEST` 설정을 'True'으로 설정하십시오. True로 설정되면 Django는 매 요청마다 데이터베이스에 세션을 저장합니다.
100)

세션 쿠키는 세션이 생성되거나 수정 된 경우에만 전송됩니다. `SESSION_SAVE_EVERY_REQUEST`True이면 모든 요청에 ​​세션 쿠키가 전송됩니다.
101)

비슷하게, 세션 쿠키의 expire 부분은 세션 쿠키가 전송 될 때마다 업데이트됩니다.
102)

응답의 상태 코드가 500이면 세션이 저장되지 않습니다.
103)

You can control whether the session framework uses browser-length sessions vs. persistent sessions with the`SESSION_EXPIRE_AT_BROWSER_CLOSE`setting.

By default,`SESSION_EXPIRE_AT_BROWSER_CLOSE`is set toFalse, which means session cookies will be stored in users’ browsers for as long as`SESSION_COOKIE_AGE`. Use this if you don’t want people to have to log in every time they open a browser.

If`SESSION_EXPIRE_AT_BROWSER_CLOSE`is set toTrue, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.

This setting is a global default and can be overwritten at a per-session level by explicitly calling the`set_expiry()`method ofrequest.sessionas described above inusing sessions in views.

Note

Some browsers (Chrome, for example) provide settings that allow users to continue browsing sessions after closing and re-opening the browser. In some cases, this can interfere with the`SESSION_EXPIRE_AT_BROWSER_CLOSE`setting and prevent sessions from expiring on browser close. Please be aware of this while testing Django applications which have the`SESSION_EXPIRE_AT_BROWSER_CLOSE`setting enabled.

As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, thedjango_sessiondatabase table will grow. If you’re using the file backend, your temporary directory will contain an increasing number of files.

To understand this problem, consider what happens with the database backend. When a user logs in, Django adds a row to thedjango_sessiondatabase table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user doesnotlog out, the row never gets deleted. A similar process happens with the file backend.

Django doesnotprovide automatic purging of expired sessions. Therefore, it’s your job to purge expired sessions on a regular basis. Django provides a clean-up management command for this purpose:`clearsessions`. It’s recommended to call this command on a regular basis, for example as a daily cron job.

Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.

Subdomains within a site are able to set cookies on the client for the whole domain. This makes session fixation possible if cookies are permitted from subdomains not controlled by trusted users.

For example, an attacker could log intogood.example.comand get a valid session for their account. If the attacker has control overbad.example.com, they can use it to send their session key to you since a subdomain is permitted to set cookies on*.example.com. When you visitgood.example.com, you’ll be logged in as the attacker and might inadvertently enter your sensitive personal data (e.g. credit card info) into the attackers account.

Another possible attack would be ifgood.example.comsets its`SESSION_COOKIE_DOMAIN` to".example.com"which would cause session cookies from that site to be sent tobad.example.com.

  • The session dictionary accepts any
    `json`
    serializable value when using
    `JSONSerializer`
    or any picklable Python object when using
    `PickleSerializer`
    . See the
    `pickle`
    module for more information.
  • Session data is stored in a database table named
    django_session
    .
  • Django only sends a cookie if it needs to. If you don’t set any session data, it won’t send a session cookie.

When working with sessions internally, Django uses a session store object from the corresponding session engine. By convention, the session store object class is namedSessionStoreand is located in the module designated by`SESSION_ENGINE`.

AllSessionStoreclasses available in Django inherit from`SessionBase`and implement data manipulation methods, namely:

In order to build a custom session engine or to customize an existing one, you may create a new class inheriting from`SessionBase`or any other existingSessionStoreclass.

Extending most of the session engines is quite straightforward, but doing so with database-backed session engines generally requires some extra effort (see the next section for details).

Creating a custom database-backed session engine built upon those included in Django (namelydbandcached_db) may be done by inheriting`AbstractBaseSession`and eitherSessionStoreclass.

AbstractBaseSessionandBaseSessionManagerare importable fromdjango.contrib.sessions.base_sessionso that they can be imported without includingdjango.contrib.sessionsin`INSTALLED_APPS`.

class

base_session.

AbstractBaseSession

The abstract base session model.

session_key

Primary key. The field itself may contain up to 40 characters. The current implementation generates a 32-character string (a random sequence of digits and lowercase ASCII letters).

session_data

A string containing an encoded and serialized session dictionary.

expire_date

A datetime designating when the session expires.

Expired sessions are not available to a user, however, they may still be stored in the database until the`clearsessions`management command is run.

classmethod

get_session_store_class

()

Returns a session store class to be used with this session model.

get_decoded

()

Returns decoded session data.

Decoding is performed by the session store class.

You can also customize the model manager by subclassing`BaseSessionManager`:

class

base_session.

BaseSessionManager

encode

(

session_dict

)

Returns the given session dictionary serialized and encoded as a string.

Encoding is performed by the session store class tied to a model class.

save

(

session_key

,

session_dict

,

expire_date

)

Saves session data for a provided session key, or deletes the session in case the data is empty.

Customization ofSessionStoreclasses is achieved by overriding methods and properties described below:

class

backends.db.

SessionStore

Implements database-backed session store.

classmethod

get_model_class

()

Override this method to return a custom session model if you need one.

create_model_instance

(

data

)

Returns a new instance of the session model object, which represents the current session state.

Overriding this method provides the ability to modify session model data before it’s saved to database.

class

backends.cached_db.

SessionStore

Implements cached database-backed session store.

cache_key_prefix

A prefix added to a session key to build a cache key string.

The example below shows a custom database-backed session engine that includes an additional database column to store an account ID (thus providing an option to query the database for all active sessions for an account):

from
django.contrib.sessions.backends.db
import
SessionStore
as
DBStore
from
django.contrib.sessions.base_session
import
AbstractBaseSession
from
django.db
import
models
class
CustomSession
(
AbstractBaseSession
):
account_id
=
models
.
IntegerField
(
null
=
True
,
db_index
=
True
)
@classmethod
def
get_session_store_class
(
cls
):
return
SessionStore
class
SessionStore
(
DBStore
):
@classmethod
def
get_model_class
(
cls
):
return
CustomSession
def
create_model_instance
(
self
,
data
):
obj
=
super
(
SessionStore
,
self
)
.
create_model_instance
(
data
)
try
:
account_id
=
int
(
data
.
get
(
'_auth_user_id'
))
except
(
ValueError
,
TypeError
):
account_id
=
None
obj
.
account_id
=
account_id
return
obj

If you are migrating from the Django’s built-incached_dbsession store to a custom one based oncached_db, you should override the cache key prefix in order to prevent a namespace clash:

class
SessionStore
(
CachedDBStore
):
cache_key_prefix
=
'mysessions.custom_cached_db_backend'
# ...

The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the “Referer” header.



1)
Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using thecookie based backend).
2)
Enabling sessions
3)
Sessions are implemented via a piece ofmiddleware.
4)
To enable session functionality, do the following:
5)
Edit the `MIDDLEWARE` setting and make sure it contains
6)
'django.contrib.sessions.middleware.SessionMiddleware'. The default settings.py created by django-admin startproject has SessionMiddleware activated.
7)
If you don’t want to use sessions, you might as well remove theSessionMiddlewareline from`MIDDLEWARE`and'django.contrib.sessions'from your`INSTALLED_APPS`. It’ll save you a small bit of overhead.
8)
Configuring the session engine
9)
By default, Django stores sessions in your database (using the modeldjango.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to store session data elsewhere, so Django can be configured to store session data on your filesystem or in your cache.
10)
Using database-backed sessions
11)
If you want to use a database-backed session, you need to add'django.contrib.sessions'to your`INSTALLED_APPS`setting.
12)
Once you have configured your installation, run manage.pymigrateto install the single database table that stores session data.
13)
Using cached sessions
14)
For better performance, you may want to use a cache-based session backend.
15)
To store session data using Django’s cache system, you’ll first need to make sure you’ve configured your cache; see thecache documentationfor details.
16)
You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments.
17)
If you have multiple caches defined in`CACHES`, Django will use the default cache. To use another cache, set`SESSION_CACHE_ALIAS`to the name of that cache.
18)
Once your cache is configured, you’ve got two choices for how to store data in the cache:
19)
Set
`SESSION_ENGINE`
to "django.contrib.sessions.backends.cache"
for a simple caching session store. Session data will be stored directly in your cache. However, session data may not be persistent: cached data can be evicted if the cache fills up or if the cache server is restarted.
20)
For persistent, cached data, set `SESSION_ENGINE`
to "django.contrib.sessions.backends.cached_db". This uses a write-through cache – every write to the cache will also be written to the database. Session reads only use the database if the data is not already in the cache.
21)
Both session stores are quite fast, but the simple cache is faster because it disregards persistence. In most cases, thecached_dbbackend will be fast enough, but if you need that last bit of performance, and are willing to let session data be expunged from time to time, thecachebackend is for you.
22)
If you use thecached_dbsession backend, you also need to follow the configuration instructions for theusing database-backed sessions.
23)
Using file-based sessions
24)
To use file-based sessions, set the`SESSION_ENGINE`setting to"django.contrib.sessions.backends.file".
25)
You might also want to set the`SESSION_FILE_PATH`setting (which defaults to output fromtempfile.gettempdir(), most likely/tmp) to control where Django stores session files. Be sure to check that your Web server has permissions to read and write to this location.
26)
Using cookie-based sessions
27)
To use cookies-based sessions, set the`SESSION_ENGINE`setting to"django.contrib.sessions.backends.signed_cookies". The session data will be stored using Django’s tools forcryptographic signingand the`SECRET_KEY`setting.
28)
It’s recommended to leave the`SESSION_COOKIE_HTTPONLY`setting onTrueto prevent access to the stored data from JavaScript.
29)
If the SECRET_KEY is not kept secret and you are using the`PickleSerializer`,this can lead to arbitrary remote code execution.
30)
An attacker in possession of the`SECRET_KEY`can not only generate falsified session data, which your site will trust, but also remotely execute arbitrary code, as the data is serialized using pickle.
31)
If you use cookie-based sessions, pay extra care that your secret key is always kept completely secret, for any system which might be remotely accessible.
32)
The session data is signed but not encrypted
33)
When using the cookies backend the session data can be read by the client.
34)
A MAC (Message Authentication Code) is used to protect the data against changes by the client, so that the session data will be invalidated when being tampered with. The same invalidation happens if the client storing the cookie (e.g. your user’s browser) can’t store all of the session cookie and drops data. Even though Django compresses the data, it’s still entirely possible to exceed thecommon limit of 4096 bytesper cookie.
35)
No freshness guarantee
36)
Note also that while the MAC can guarantee the authenticity of the data (that it was generated by your site, and not someone else), and the integrity of the data (that it is all there and correct), it cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client. This means that for some uses of session data, the cookie backend might open you up toreplay attacks. Unlike other session backends which keep a server-side record of each session and invalidate it when a user logs out, cookie-based sessions are not invalidated when a user logs out. Thus if an attacker steals a user’s cookie, they can use that cookie to login as that user even if the user logs out. Cookies will only be detected as ‘stale’ if they are older than your`SESSION_COOKIE_AGE`.
37)
Performance
38)
Finally, the size of a cookie can have an impact on thespeed of your site.
40)
WhenSessionMiddlewareis activated, each`HttpRequest`object – the first argument to any Django view function – will have asessionattribute, which is a dictionary-like object.
41)
You can read it and write torequest.sessionat any point in your view. You can edit it multiple times.
42)
This is the base class for all session objects. It has the following standard dictionary methods:
43)
This raises KeyErrorif the givenkeyisn’t already in the session.
44)
It also has these methods:
45)
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the`django.contrib.auth.logout()`function calls it).
46)
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. SeeSetting test cookiesbelow for more information.
47)
Returns eitherTrueorFalse, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to callset_test_cookie()on a previous, separate page request. SeeSetting test cookiesbelow for more information.
48)
Deletes the test cookie. Use this to clean up after yourself.
49)
Sets the expiration time for the session. You can pass a number of different values:
50)
* If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes.
51)
* If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the `PickleSerializer`.
52)
* If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.
53)
* If value is None, the session reverts to using the global session expiry policy.
54)
Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.
55)
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal`SESSION_COOKIE_AGE`.
56)
This function accepts two optional keyword arguments:
57)
* modification: last modification of the session, as a `datetime` object. Defaults to the current time.
58)
* expiry: expiry information for the session, as a `datetime` object, an
`int` (in seconds), or
None. Defaults to the value stored in the session by `set_expiry()`, if there is one, or None.
59)
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date `SESSION_COOKIE_AGE` seconds from now.
60)
This function accepts the same keyword arguments as`get_expiry_age()`.
61)
Returns eitherTrueorFalse, depending on whether the user’s session cookie will expire when the user’s Web browser is closed.
62)
Removes expired sessions from the session store. This class method is called by`clearsessions`.
63)
Creates a new session key while retaining the current session data.`django.contrib.auth.login()`calls this method to mitigate against session fixation.
64)
Session serialization
65)
By default, Django serializes session data using JSON. You can use the`SESSION_SERIALIZER`setting to customize the session serialization format.
66)
Even with the caveats described in Write your own serializer, we highly recommend sticking with JSON serialization especially if you are using the cookie backend.
67)
For example, here’s an attack scenario if you use `pickle` to serialize session data. If you’re using thesigned cookie session backend and `SECRET_KEY` is known by an attacker (there isn’t an inherent vulnerability in Django that would cause it to leak), the attacker could insert a string into their session which, when unpickled, executes arbitrary code on the server. The technique for doing so is simple and easily available on the internet. Although the cookie session storage signs the cookie-stored data to prevent tampering, a `SECRET_KEY` leak immediately escalates to a remote code execution vulnerability.
69)
A wrapper around the JSON serializer from`django.core.signing`. Can only serialize basic data types.
70)
In addition, as JSON supports only string keys, note that using non-string keys inrequest.session won’t work as expected:
71)
Similarly, data that can’t be encoded in JSON, such as non-UTF8 bytes like'\xd9'(which raises `UnicodeDecodeError`), can’t be stored.
72)
See theWrite your own serializer section for more details on limitations of JSON serialization.
73)
Supports arbitrary Python objects, but, as described above, can lead to a remote code execution vulnerability if`SECRET_KEY`becomes known by an attacker.
74)
Note that unlike`PickleSerializer`, the`JSONSerializer`cannot handle arbitrary Python data types. As is often the case, there is a trade-off between convenience and security.
75)
If you wish to store more advanced data types including datetime and Decimal in JSON backed sessions, you will need to write a custom serializer (or convert such values to a JSON serializable object before storing them in request.session). While serializing these values is fairly straightforward (`DjangoJSONEncoder`may be helpful), writing a decoder that can reliably get back the same thing that you put in is more fragile.
76)
For example, you run the risk of returning adatetime that was actually a string that just happened to be in the same format chosen fordatetimes.
77)
Your serializer class must implement two methods,dumps(self,obj) and loads(self,data), to serialize and deserialize the dictionary of session data, respectively.
78)

* Use normal Python strings as dictionary keys on request.session. This is more of a convention than a hard-and-fast rule.
79)
* Session dictionary keys that begin with an underscore are reserved for internal use by Django.
80)
* Don’t override request.session with a new object, and don’t access or set its attributes. Use it like a Python dictionary.
81)
This simplistic view sets ahas_commented variable to True after a user posts a comment. It doesn’t let a user post a comment more than once:
82)
This simplistic view logs in a “member” of the site:
83)
…And this one logs a member out, according to login() above:
84)
The standard `django.contrib.auth.logout()`function actually does a bit more than this to prevent inadvertent data leakage. It calls the`flush()`method of request.session. We are using this example as a demonstration of how to work with session objects, not as a full logout() implementation.
85)
Setting test cookies
86)
As a convenience, Django provides an easy way to test whether the user’s browser accepts cookies.
87)

Just call the `set_test_cookie()`method of request.session in a view, and call`test_cookie_worked()`in a subsequent view – not in the same view call.
88)
This awkward split between set_test_cookie() and test_cookie_worked() is necessary due to the way cookies work. When you set a cookie, you can’t actually tell whether a browser accepted it until the browser’s next request.
89)
It’s good practice to use `delete_test_cookie()`to clean up after yourself. Do this after you’ve verified that the test cookie worked.
90)
Here’s a typical usage example:
91)
Using sessions out of views
92)
The examples in this section import theSessionStoreobject directly from thedjango.contrib.sessions.backends.dbbackend. In your own code, you should consider importingSessionStorefrom the session engine designated by`SESSION_ENGINE`, as below:
93)
An API is available to manipulate session data outside of a view:
94)
SessionStore.create() is designed to create a new session (i.e. one not loaded from the session store and withsession_key=None).save() is designed to save an existing session (i.e. one loaded from the session store). Calling save() on a new session may also work but has a small chance of generating asession_keythat collides with an existing one. create() calls save() and loops until an unused session_key is generated.
95)
If you’re using the django.contrib.sessions.backends.db backend, each session is just a normal Django model. The Session model is defined in django/contrib/sessions/models.py. Because it’s a normal model, you can access sessions using the normal Django database API:
96)
Note that you’ll need to call `get_decoded()`to get the session dictionary. This is necessary because the dictionary is stored in an encoded format:
97)
When sessions are saved
98)
By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted:
99)
In the last case of the above example, we can tell the session object explicitly that it has been modified by setting themodifiedattribute on the session object:
100)
To change this default behavior, set the `SESSION_SAVE_EVERY_REQUEST`setting to True. When set to True, Django will save the session to the database on every single request.
101)
Note that the session cookie is only sent when a session has been created or modified. If `SESSION_SAVE_EVERY_REQUEST` is True, the session cookie will be sent on every request.
102)
Similarly, the expires part of a session cookie is updated each time the session cookie is sent.
103)
The session is not saved if the response’s status code is 500.
  • open/django-세션-사용하기.txt
  • 마지막으로 수정됨: 2020/07/15 08:48
  • 저자 127.0.0.1