Django 세션 사용하기 ((How to use sessions))
원문 : https://docs.djangoproject.com/en/1.11/topics/http/sessions/
Django는 익명 세션을 완벽하게 지원합니다. 세션 프레임워크를 사용하면 사이트 방문자별로 임의의 데이터를 저장하고 검색 할 수 있습니다. 서버 측에 데이터를 저장하고 쿠키 송수신을 추상화합니다. 쿠키에는 세션 ID가 들어 있지만 데이터 자체는 아닙니다. (쿠키 기반 백엔드를 사용하지 않는 한)
1)
세션 활성화
세션 기능을 사용하려면 다음을 수행하십시오.
4)
django.contrib.sessions.middleware.SessionMiddleware
에 의해 만들어진 settings.py 기본 설정django-admin startproject
는SessionMiddleware
를 활성화했습니다.
6)
세션을 사용하고 싶지 않은 경우에는 `MIDDLEWARE`에서 'SessionMiddlewareline '을 삭제하고 `INSTALLED_APPS`에서는 'django.contrib.sessions'를 삭제할 수 있습니다. 약간의 오버 헤드를 줄일 수 있습니다.
7)
세션 엔진 설정하기
기본적으로 Django는 데이터베이스에 세션을 저장합니다 (모델 django.contrib.sessions.models.Session
). 이 설정은 편리하지만 일부 설정에서는 세션 데이터를 다른 곳에 저장하는 것이 더 빠르기 때문에 파일 시스템이나 캐시에 세션 데이터를 저장하도록 Django를 구성 할 수 있습니다.
9)
데이터베이스 기반 세션 사용하기
데이터베이스 기반 세션을 사용하려면 django.contrib.sessions
를 `INSTALLED_APPS`에 추가해야합니다.
11)
설치를 구성한 후에는manage.pymigrate
를 실행하여 세션 데이터를 저장하는 단일 데이터베이스 테이블을 설치하십시오.
12)
캐시 기반 세션 사용하기
성능 향상을 위해 캐시 기반 세션 백엔드를 사용할 수 있습니다.
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)
파일기반 세션 사용하기
파일 기반 세션을 사용하려면 `SESSION_ENGINE` 설정에 django.contrib.sessions.backends.file
을 설정합니다.
24)
`SESSION_FILE_PATH` 설정을 원할 수도 있습니다 (기본값은 tempfile.gettempdir ()
, 가장 가능성있는 /tmp
)를 사용하여 Django가 세션 파일을 저장하는 위치를 제어 할 수 있습니다. 웹서버의 위치를 읽고 쓸 수있는 권한이 있는지 확인하십시오.
25)
쿠키 기반 세션 사용하기
쿠키 기반 세션을 사용하려면 `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)
뷰에서 세션 사용하기
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)
set_test_cookie()
테스트 쿠키를 설정하여 사용자 브라우저가 쿠키를 지원하는지 여부를 결정합니다. 쿠키가 작동하는 방식 때문에 사용자가 다음 페이지 요청을 할 때까지이를 테스트 할 수 없습니다. 자세한 내용은 아래의 테스트 쿠키 설정을 참조하십시오.
46)
test_cookie_worked()
사용자 브라우저가 테스트 쿠키를 수락했는지 여부에 따라 True
또는False
를 반환합니다. 쿠키가 작동하는 방식 때문에 이전의 별도의 페이지 요청에서 set_test_cookie ()
를 호출해야합니다. 자세한 내용은 아래의 테스트 쿠키 설정을 참조하십시오.
47)
delete_test_cookie()
테스트 쿠키를 삭제합니다. 이것을 사용하여 자신을 정리하십시오.
48)
set_expiry(value)
세션의 만기 시간을 설정합니다. 다양한 값을 전달할 수 있습니다.
49)
- 만약
value
가 정수이면 몇 초 동안 활동하지 않으면 세션이 만료됩니다. 예를 들어, 호출
request.session.set_expiry (300)
를 호출하면 5분 안에 세션이 만료됩니다.
50)
value
가datetime
또는timedelta
객체라면, 세션은 그 특정 날짜/시간에 만료 될 것입니다. PickleSerializer를 사용하는 경우datetime
과timedelta
값은 직렬화 가능합니다.
51)
세션 읽기는 만료 목적의 활동으로 간주되지 않습니다. 세션 만료는 세션이 마지막으로 수정 된 시간부터 계산됩니다.
54)
get_expiry_age()
이 세션이 만료 할 때까지의 초 수를 반환합니다. 사용자 정의 만료가없는 세션 (또는 브라우저 닫기에서 만료되도록 설정 한 세션)의 경우이 값은 `SESSION_COOKIE_AGE`와 같습니다.
55)
이 함수는 두 개의 선택적 키워드 인수를 허용합니다.
56)
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)
세션 직렬화
기본적으로 장고는 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)
번들 직렬화
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)
class serializers.PickleSerializer
임의의 파이썬 개체를 지원하지만 위에서 설명한대로 `SECRET_KEY`가 있으면 원격 코드 실행 취약점이 발생할 수 있습니다. )가 공격자에게 알려지게 됩니다.
73)
Write your own serializer
`PickleSerializer`와 달리 `JSONSerializer` 임의의 파이썬 데이터 유형을 처리 할 수 없습니다. 종종 그렇듯이 편의성과 보안 성 사이에는 트레이드 오프가 있습니다.
74)
datetime
과 Decimal
을 포함한 더 진보 된 데이터 타입을 JSON 지원 세션에 저장하고 싶다면, 커스텀 시리얼 라이저를 작성하거나 (request.session
에 저장하기 전에 이러한 값을 JSON 직렬화 가능한 객체로 변환해야합니다). 이러한 값을 직렬화하는 것은 매우 간단합니다 (`DjangoJSONEncoder` 도움이 될 수 있습니다. 디코더는 안정적으로 당신이 넣는 것과 똑같은 것을 되 찾을 수 있습니다.
75)
예를 들어 datetime
을 반환 할 위험이 있습니다. 실제로는 datetime
과 같은 형식으로 된 문자열입니다.
76)
serializer 클래스는 세션 데이터의 사전을 직렬화 및 비 직렬화하는 두 가지 메소드, dumps(self, obj)
및 loads(self, data)
를 구현해야 합니다.
77)
Session object guidelines
Examples
이 간단한보기는 사용자가 주석을 게시 한 후 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)
테스트 쿠키 설정
편의상 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')
뷰가 아닌 세션 사용
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}
세션 저장시
기본적으로 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)
Browser-length sessions vs. persistent sessions[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions)
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.session
as 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.
Clearing the session store[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#clearing-the-session-store)
As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, thedjango_session
database 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_session
database 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.
Settings[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#settings)
A fewDjango settingsgive you control over session behavior:
Session security[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#session-security)
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.com
and 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.com
sets its`SESSION_COOKIE_DOMAIN` to".example.com"
which would cause session cookies from that site to be sent tobad.example.com
.
Technical details[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#technical-details)
- 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.
The`SessionStore`object[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#the-sessionstore-object)
When working with sessions internally, Django uses a session store object from the corresponding session engine. By convention, the session store object class is namedSessionStore
and is located in the module designated by`SESSION_ENGINE`.
AllSessionStore
classes available in Django inherit from`SessionBase`and implement data manipulation methods, namely:
exists()
create()
save()
delete()
load()
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 existingSessionStore
class.
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).
Extending database-backed session engines[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#extending-database-backed-session-engines)
Creating a custom database-backed session engine built upon those included in Django (namelydb
andcached_db
) may be done by inheriting`AbstractBaseSession`and eitherSessionStore
class.
AbstractBaseSession
andBaseSessionManager
are importable fromdjango.contrib.sessions.base_session
so that they can be imported without includingdjango.contrib.sessions
in`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 ofSessionStore
classes 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.
Example[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#example)
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_db
session 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' # ...
Session IDs in URLs[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#session-ids-in-urls)
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.
관련 문서
'django.contrib.sessions.middleware.SessionMiddleware'
. The default settings.py created by django-admin startproject
has SessionMiddleware
activated.SessionMiddleware
line from`MIDDLEWARE`and'django.contrib.sessions'
from your`INSTALLED_APPS`. It’ll save you a small bit of overhead.django.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.'django.contrib.sessions'
to your`INSTALLED_APPS`setting.manage.pymigrate
to install the single database table that stores session data.`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.
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.cached_db
backend 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, thecache
backend is for you.cached_db
session backend, you also need to follow the configuration instructions for theusing database-backed sessions."django.contrib.sessions.backends.file"
.tempfile.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."django.contrib.sessions.backends.signed_cookies"
. The session data will be stored using Django’s tools forcryptographic signingand the`SECRET_KEY`setting.True
to prevent access to the stored data from JavaScript.SessionMiddleware
is activated, each`HttpRequest`object – the first argument to any Django view function – will have asession
attribute, which is a dictionary-like object.request.session
at any point in your view. You can edit it multiple times.KeyError
if the givenkey
isn’t already in the session.True
orFalse
, 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.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.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`.value
is 0
, the user’s session cookie will expire when the user’s Web browser is closed.value
is None
, the session reverts to using the global session expiry policy.modification
: last modification of the session, as a `datetime` object. Defaults to the current time.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
.True
orFalse
, depending on whether the user’s session cookie will expire when the user’s Web browser is closed.request.session
won’t work as expected:'\xd9'
(which raises `UnicodeDecodeError`), can’t be stored.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.datetime
that was actually a string that just happened to be in the same format chosen fordatetime
s.dumps(self,obj)
and loads(self,data)
, to serialize and deserialize the dictionary of session data, respectively.* Use normal Python strings as dictionary keys on
request.session
. This is more of a convention than a hard-and-fast rule.request.session
with a new object, and don’t access or set its attributes. Use it like a Python dictionary.has_commented
variable to True
after a user posts a comment. It doesn’t let a user post a comment more than once:login()
above:request.session
. We are using this example as a demonstration of how to work with session objects, not as a full logout()
implementation.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.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.SessionStore
object directly from thedjango.contrib.sessions.backends.db
backend. In your own code, you should consider importingSessionStore
from the session engine designated by`SESSION_ENGINE`, as below: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_key
that collides with an existing one. create()
calls save()
and loops until an unused session_key
is generated.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:modified
attribute on the session object:True
. When set to True
, Django will save the session to the database on every single request.True
, the session cookie will be sent on every request.expires
part of a session cookie is updated each time the session cookie is sent.