문서 보기역링크PDF로 내보내기맨 위로 이 문서는 읽기 전용입니다. 원본을 볼 수는 있지만 바꿀 수는 없습니다. 문제가 있다고 생각하면 관리자에게 문의하세요. # Django 세션 사용하기 ((How to use sessions)) {{tag>Django 세션 session}} 원문 : https://docs.djangoproject.com/en/1.11/topics/http/sessions/ Django는 익명 세션을 완벽하게 지원합니다. 세션 프레임워크를 사용하면 사이트 방문자별로 임의의 데이터를 저장하고 검색 할 수 있습니다. 서버 측에 데이터를 저장하고 쿠키 송수신을 추상화합니다. 쿠키에는 세션 ID가 들어 있지만 데이터 자체는 아닙니다. (쿠키 기반 백엔드를 사용하지 않는 한) ((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 the[cookie based backend](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#cookie-session-backend)).)) ## 세션 활성화 ((Enabling sessions)) 세션은 [미들웨어](https://docs.djangoproject.com/en/1.11/ref/middleware/)를 통해 구현됩니다.((Sessions are implemented via a piece of[middleware](https://docs.djangoproject.com/en/1.11/ref/middleware/).)) 세션 기능을 사용하려면 다음을 수행하십시오. ((To enable session functionality, do the following:)) - [`MIDDLEWARE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MIDDLEWARE) 설정하고 포함되어 있는지 확인하십시오. ((Edit the [`MIDDLEWARE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MIDDLEWARE) setting and make sure it contains)) - `django.contrib.sessions.middleware.SessionMiddleware`에 의해 만들어진 **settings.py** 기본 설정 `django-admin startproject`는 `SessionMiddleware`를 활성화했습니다. ((`'django.contrib.sessions.middleware.SessionMiddleware'`. The default **settings.py** created by `django-admin startproject` has `SessionMiddleware` activated.)) 세션을 사용하고 싶지 않은 경우에는 [`MIDDLEWARE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MIDDLEWARE)에서 'SessionMiddlewareline '을 삭제하고 [`INSTALLED_APPS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS)에서는 'django.contrib.sessions'를 삭제할 수 있습니다. 약간의 오버 헤드를 줄일 수 있습니다. ((If you don’t want to use sessions, you might as well remove the`SessionMiddleware`line from[`MIDDLEWARE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MIDDLEWARE)and`'django.contrib.sessions'`from your[`INSTALLED_APPS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS). It’ll save you a small bit of overhead.)) ## 세션 엔진 설정하기 ((Configuring the session engine)) 기본적으로 Django는 데이터베이스에 세션을 저장합니다 (모델 `django.contrib.sessions.models.Session` ). 이 설정은 편리하지만 일부 설정에서는 세션 데이터를 다른 곳에 저장하는 것이 더 빠르기 때문에 파일 시스템이나 캐시에 세션 데이터를 저장하도록 Django를 구성 할 수 있습니다. ((By default, Django stores sessions in your database \(using the model`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.)) ### 데이터베이스 기반 세션 사용하기 ((Using database-backed sessions)) 데이터베이스 기반 세션을 사용하려면 `django.contrib.sessions`를 [`INSTALLED_APPS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS)에 추가해야합니다. ((If you want to use a database-backed session, you need to add`'django.contrib.sessions'`to your[`INSTALLED_APPS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS)setting.)) 설치를 구성한 후에는`manage.pymigrate`를 실행하여 세션 데이터를 저장하는 단일 데이터베이스 테이블을 설치하십시오. ((Once you have configured your installation, run `manage.pymigrate`to install the single database table that stores session data.)) ### 캐시 기반 세션 사용하기 ((Using cached sessions)) 성능 향상을 위해 캐시 기반 세션 백엔드를 사용할 수 있습니다. ((For better performance, you may want to use a cache-based session backend.)) Django의 캐시 시스템을 사용하여 세션 데이터를 저장하려면 먼저 캐시를 구성했는지 확인해야합니다. 자세한 내용은 [cache documentation](https://docs.djangoproject.com/en/1.11/topics/cache/)를 참조하십시오. ((To store session data using Django’s cache system, you’ll first need to make sure you’ve configured your cache; see the[cache documentation](https://docs.djangoproject.com/en/1.11/topics/cache/)for details.)) <WRAP info> Memcached 캐시 백엔드를 사용하는 경우에만 캐시 기반 세션을 사용해야합니다. 로컬 메모리 캐시 백엔드는 데이터를 충분히 길게 유지하지 않으며, 파일 또는 데이터베이스 캐시 백엔드를 통해 모든 것을 보내는 대신 직접 파일 또는 데이터베이스 세션을 사용하는 것이 빠릅니다. 또한 로컬 메모리 캐시 백엔드는 다중 프로세스 안전이 아니므로 프로덕션 환경에 적합하지 않을 수 있습니다. ((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.)) </WRAP> [CACHES](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-CACHES)에 정의 된 캐시가 여러 개인 경우 Django는 기본 캐시를 사용합니다. 다른 캐시를 사용하려면 해당 캐시의 이름을 [`SESSION_CACHE_ALIAS`](https://docs.djangoproject.com/en/1.st/ref/settings/#std:setting-SESSION_CACHE_ALIAS)로 설정하십시오. ((If you have multiple caches defined in[`CACHES`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-CACHES), Django will use the default cache. To use another cache, set[`SESSION_CACHE_ALIAS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_CACHE_ALIAS)to the name of that cache.)) 캐시가 구성되면 캐시에 데이터를 저장하는 방법에 대해 두 가지 선택 사항이 있습니다. ((Once your cache is configured, you’ve got two choices for how to store data in the cache:)) - [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE) 에 `django.contrib.sessions.backends.cache`을 설정합니다. 간단한 캐싱 세션 저장소. 세션 데이터는 캐시에 직접 저장됩니다. 그러나 세션 데이터가 지속되지 않을 수 있습니다. 캐시가 가득 차거나 캐시 서버가 다시 시작되면 캐시 된 데이터가 제거 될 수 있습니다. ((Set [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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.)) - 지속적이고 캐시 된 데이터의 경우 [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE)에 `django.contrib.sessions.backends.cached_db`을 설정합니다. 이것은 연속 기입 캐시를 사용합니다. 캐시에 대한 모든 쓰기도 데이터베이스에 기록됩니다. 세션 읽기는 데이터가 캐시에없는 경우에만 데이터베이스를 사용합니다. ((For persistent, cached data, set [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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.)) 두 세션 저장소는 모두 빠르지 만 지속성을 무시하기 때문에 단순한 캐시가 빠릅니다. 대부분의 경우,`cached_db` 백엔드는 충분히 빠르지 만 성능의 마지막 비트가 필요하고 때때로 세션 데이터를 소멸 시키려고한다면 `cache` 백엔드가 당신을위한 것입니다. ((Both session stores are quite fast, but the simple cache is faster because it disregards persistence. In most cases, the`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, the`cache`backend is for you.)) `cached_db` 세션 백엔드를 사용한다면, [데이터베이스 기반 세션 사용하기](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-database-backed-sessions)에 대한 설정 지시 사항을 따라야합니다. ((If you use the`cached_db`session backend, you also need to follow the configuration instructions for the[using database-backed sessions](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-database-backed-sessions).)) ### 파일기반 세션 사용하기 ((Using file-based sessions)) 파일 기반 세션을 사용하려면 [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE) 설정에 `django.contrib.sessions.backends.file`을 설정합니다. ((To use file-based sessions, set the[`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE)setting to`"django.contrib.sessions.backends.file"`.)) [`SESSION_FILE_PATH`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_FILE_PATH) 설정을 원할 수도 있습니다 (기본값은 `tempfile.gettempdir ()`, 가장 가능성있는 `/tmp`)를 사용하여 Django가 세션 파일을 저장하는 위치를 제어 할 수 있습니다. 웹서버의 위치를 읽고 쓸 수있는 권한이 있는지 확인하십시오. ((You might also want to set the[`SESSION_FILE_PATH`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_FILE_PATH)setting \(which defaults to output from`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.)) ### 쿠키 기반 세션 사용하기 ((Using cookie-based sessions)) 쿠키 기반 세션을 사용하려면 [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE)에 `django.contrib.sessions.backends.signed_cookies`을 설정하십시오. 세션 데이터는 Django의 [암호화 서명](https://docs.djangoproject.com/en/1.11/topics/signing/) 및 [`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY) 도구를 사용하여 저장됩니다. ((To use cookies-based sessions, set the[`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE)setting to`"django.contrib.sessions.backends.signed_cookies"`. The session data will be stored using Django’s tools for[cryptographic signing](https://docs.djangoproject.com/en/1.11/topics/signing/)and the[`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY)setting.)) <WRAP tip> Note 자바 스크립트에서 저장된 데이터에 액세스하지 못하도록 하려면 [`SESSION_COOKIE_HTTPONLY`](https://docs.djangoproject.com/en/1.st/:settings/SESSION_COOKIE_HTTPONLY) 설정을 `True`로 설정하는 것이 좋습니다. ((It’s recommended to leave the[`SESSION_COOKIE_HTTPONLY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_HTTPONLY)setting on`True`to prevent access to the stored data from JavaScript.)) </WRAP> <WRAP info> Warning **SECRET_KEY가 비밀로 유지되지 않고** [`PickleSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer)를 사용하고 있다면, **이로 인해 임의의 원격 코드 실행이 발생할 수 있습니다.** ((**If the SECRET\_KEY is not kept secret and you are using the**[`PickleSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer),**this can lead to arbitrary remote code execution.**)) [SECRET_KEY](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY)를 소유 한 공격자는 사이트가 신뢰할 수 있는 위조된 세션 데이터 생성 뿐만 아니라. pickle을 사용하여 데이터가 직렬화되기 때문에 원격으로 임의의 코드를 실행할수 있습니다. ((An attacker in possession of the[`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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.)) 쿠키 기반 세션을 사용하는 경우 원격으로 액세스 할 수 있는 시스템의 경우 항상 `비밀키`가 항상 비밀로 유지되어야 합니다. ((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.)) **세션 데이터는 서명되었지만 암호화되지 않았습니다.** ((**The session data is signed but not encrypted**)) 쿠키 백엔드를 사용할 때 클라이언트가 세션 데이터를 읽을 수 있습니다. ((When using the cookies backend the session data can be read by the client.)) MAC(Message Authentication Code)는 클라이언트가 변경 한 데이터를 보호하기 위해 사용되므로 세션 데이터가 변조 될 때 무효화됩니다. 쿠키를 저장하는 클라이언트 (예: 사용자의 브라우저)가 모든 세션 쿠키를 저장하고 데이터를 삭제할 수없는 경우에도 동일한 무효화가 발생합니다. Django가 데이터를 압축하더라도 cookie 당 [4096 bytes 제한](https://tools.ietf.org/html/rfc2965#section-5.3)을 초과 할 수 있습니다. ((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 the[common limit of 4096 bytes](https://tools.ietf.org/html/rfc2965#section-5.3)per cookie.)) **최신에 대한 보장을 못함** ((**No freshness guarantee**)) 또한 MAC가 데이터의 진위성을 보장 할 수 있지만 (데이터가 사이트 및 다른 사람이 생성하지 않음) 데이터의 무결성을 보장 할 수 있지만 (데이터가 모두 있고 올바른), 신선도를 보장합니다. 즉, 클라이언트에 마지막으로 보낸 것을 다시 보냈습니다. 즉, 세션 데이터를 일부 사용하는 경우 쿠키 백엔드가 [replay attacks](https://en.wikipedia.org/wiki/Replay_attack)까지 열 수 있습니다. 사용자가 로그 아웃 할 때 각 세션의 서버 측 기록을 유지하고 무효화하는 다른 세션 백엔드와 달리, 사용자가 로그 아웃 할 때 쿠키 기반 세션은 무효화되지 않습니다. 따라서 공격자가 사용자의 쿠키를 훔칠 경우 해당 쿠키를 사용하여 사용자가 로그 아웃하더라도 해당 사용자로 로그인 할 수 있습니다. 쿠키가 [`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/1.st/ref/settings/#std:setting-SESSION_COOKIE_AGE)보다 오래된 경우 쿠키는 '부실함(stale)'으로 만 감지됩니다. ((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 to[replay attacks](https://en.wikipedia.org/wiki/Replay_attack). 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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE).)) **성능** ((**Performance**)) 마지막으로, 쿠키의 크기는 [사이트 속도](https://yuiblog.com/blog/2007/03/01/performance-research-part-3/)에 영향을 줄 수 있습니다. ((Finally, the size of a cookie can have an impact on the[speed of your site](https://yuiblog.com/blog/2007/03/01/performance-research-part-3/).)) </WRAP> ## 뷰에서 세션 사용하기 (([Using sessions in views](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-sessions-in-views))) `SessionMiddleware`가 활성화되면 각각의 [`HttpRequest`](https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest) 객체 - Django 뷰의 첫 번째 인수 함수 - 사전과 같은 객체인 '세션'속성을 갖습니다. ((When`SessionMiddleware`is activated, each[`HttpRequest`](https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest)object – the first argument to any Django view function – will have a`session`attribute, which is a dictionary-like object.)) 당신은 당신의 관점에서 그것을 읽고 `request.session`에 쓸 수 있습니다. 여러 번 편집 할 수 있습니다. ((You can read it and write to`request.session`at any point in your view. You can edit it multiple times.)) #### class backends.base.SessionBase 이것은 모든 세션 객체의 기본 클래스입니다. 다음과 같은 표준 사전 방법이 있습니다. ((This is the base class for all session objects. It has the following standard dictionary methods:)) ##### __getitem__(key) ```python Example: fav_color=request.session['fav_color'] ``` ##### __setitem__(key, value) ```python Example: request.session['fav_color']='blue' ``` ##### __delitem__(key) ```python Example: del request.session['fav_color']. ``` 주어진 키가 이미 세션에없는 경우 이것은 `KeyError`를 발생시킵니다. ((This raises `KeyError`if the given`key`isn’t already in the session.)) ##### __contains__(key) ```python Example: 'fav_color' in request.session ``` ##### get(key, default=None) ```python Example: fav_color=request.session.get('fav_color','red') ``` ##### pop(key, default=__not_given) ```python Example: fav_color=request.session.pop('fav_color','blue') ``` ##### keys() ##### items() ##### setdefault() ##### clear() 또한 다음과 같은 방법이 있습니다.((It also has these methods:)) ##### flush() 세션에서 현재 세션 데이터를 삭제하고 세션 쿠키를 삭제합니다. 이것은 사용자의 브라우저에서 이전 세션 데이터에 다시 액세스 할 수 없도록 하려는 경우에 사용됩니다 (예 : [`django.contrib.auth.logout()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout) 함수를 호출합니다. ((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()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout)function calls it\).)) ##### set_test_cookie() 테스트 쿠키를 설정하여 사용자 브라우저가 쿠키를 지원하는지 여부를 결정합니다. 쿠키가 작동하는 방식 때문에 사용자가 다음 페이지 요청을 할 때까지이를 테스트 할 수 없습니다. 자세한 내용은 아래의 [테스트 쿠키 설정](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#setting-test-cookies)을 참조하십시오. ((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. See[Setting test cookies](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#setting-test-cookies)below for more information.)) ##### test_cookie_worked() 사용자 브라우저가 테스트 쿠키를 수락했는지 여부에 따라 `True`또는`False`를 반환합니다. 쿠키가 작동하는 방식 때문에 이전의 별도의 페이지 요청에서 `set_test_cookie ()`를 호출해야합니다. 자세한 내용은 아래의 [테스트 쿠키 설정](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#setting-test-cookies)을 참조하십시오. ((Returns either`True`or`False`, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call`set_test_cookie()`on a previous, separate page request. See[Setting test cookies](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#setting-test-cookies)below for more information.)) ##### delete_test_cookie() 테스트 쿠키를 삭제합니다. 이것을 사용하여 자신을 정리하십시오. ((Deletes the test cookie. Use this to clean up after yourself.)) ##### set_expiry(value) 세션의 만기 시간을 설정합니다. 다양한 값을 전달할 수 있습니다. ((Sets the expiration time for the session. You can pass a number of different values:)) - 만약 `value`가 정수이면 몇 초 동안 활동하지 않으면 세션이 만료됩니다. 예를 들어, 호출 `request.session.set_expiry (300)`를 호출하면 5분 안에 세션이 만료됩니다. ((* 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.)) - `value`가 `datetime` 또는`timedelta` 객체라면, 세션은 그 특정 날짜/시간에 만료 될 것입니다. [PickleSerializer](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions)를 사용하는 경우 `datetime`과`timedelta` 값은 직렬화 가능합니다. ((* 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`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer).)) - `value`가 `0`이면 사용자의 웹 브라우저가 닫힐 때 세션 쿠키가 만료됩니다. ((* If `value` is `0`, the user’s session cookie will expire when the user’s Web browser is closed.)) - `value`가 `None`이면, 세션은 전역 세션 만료 정책을 사용하는 것으로 되돌아갑니다. ((* If `value` is `None`, the session reverts to using the global session expiry policy.)) 세션 읽기는 만료 목적의 활동으로 간주되지 않습니다. 세션 만료는 세션이 마지막으로 수정 된 시간부터 계산됩니다. ((Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was _modified_.)) ##### get_expiry_age() 이 세션이 만료 할 때까지의 초 수를 반환합니다. 사용자 정의 만료가없는 세션 (또는 브라우저 닫기에서 만료되도록 설정 한 세션)의 경우이 값은 [`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE)와 같습니다. ((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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE).)) 이 함수는 두 개의 선택적 키워드 인수를 허용합니다. ((This function accepts two optional keyword arguments:)) - `modification` : 세션의 마지막 수정으로서 [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) 객체입니다. 기본값은 현재 시간입니다. ((* `modification`: last modification of the session, as a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) object. Defaults to the current time.)) - `expiry` : 세션의 만기 정보 [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) 객체, [`int`](https://docs.python.org/3/library/functions.html#int) (초 단위) 또는 'None'. 기본값은 [`set_expiry()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry)에 의해 세션에 저장된 값입니다. 하나가 있거나 'None'. ((* `expiry`: expiry information for the session, as a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) object, an [`int`](https://docs.python.org/3/library/functions.html#int) (in seconds), or `None`. Defaults to the value stored in the session by [`set_expiry()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry), if there is one, or `None`.)) ##### get_expiry_date() 이 세션이 기한 마감일을 반환합니다. 사용자 정의 만료가없는 세션 (또는 브라우저 닫기에서 만료되도록 설정 한 세션)의 경우이 값은 [`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE) 지금부터 날짜 초와 같습니다. ((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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE) seconds from now.)) 이 함수는 [get_expiry_age()](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.get_expiry_age)와 동일한 키워드 인수를 받습니다 ((This function accepts the same keyword arguments as[`get_expiry_age()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.get_expiry_age).)) ##### get_expire_at_browser_close() 사용자의 웹 브라우저가 닫힐 때 세션 쿠키가 만료되는지 여부에 따라 `True` 또는 `False`를 반환합니다. ((Returns either`True`or`False`, depending on whether the user’s session cookie will expire when the user’s Web browser is closed.)) ##### clear_expired() 만료 된 세션을 세션 저장소에서 제거합니다. 이 클래스 메소드는 [`clearsessions`](https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-clearsessions)에 의해 호출됩니다. ((Removes expired sessions from the session store. This class method is called by[`clearsessions`](https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-clearsessions).)) ##### cycle_key() 현재 세션 데이터를 유지하면서 새 세션 키를 만듭니다. [`django.contrib.auth.login ()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib .auth.login)은 세션 고정에 대한 완화를 위해이 메소드를 호출합니다. ((Creates a new session key while retaining the current session data.[`django.contrib.auth.login()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login)calls this method to mitigate against session fixation.)) ### 세션 직렬화 ((Session serialization)) 기본적으로 장고는 JSON을 사용하여 세션 데이터를 직렬화합니다. [`SESSION_SERIALIZER`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SERIALIZER) 설정을 사용하여 세션 직렬화 형식을 사용자 정의 할 수 있습니다. ((By default, Django serializes session data using JSON. You can use the[`SESSION_SERIALIZER`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SERIALIZER)setting to customize the session serialization format.)) [자신의 시리얼 라이저 작성] (https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers)에 설명 된주의 사항이 있더라도 JSON 직렬화를 사용하는 것이 좋습니다. 특히 사용중인 경우 쿠키 백엔드. 특히 쿠키 백엔드를 사용중이라면 [자신의 직렬화 작성](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers)에 설명 된주의 사항이 있더라도 JSON 직렬화를 사용하는 것이 좋습니다. ((Even with the caveats described in [Write your own serializer](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers), we highly recommend sticking with JSON serialization especially if you are using the cookie backend.)) 예를 들어, [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle)을 사용하여 세션 데이터를 직렬화하는 경우 공격 시나리오가 있습니다. [서명 된 쿠키 세션 백엔드](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#cookie-session-backend) 및 [`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY))를 사용하는 경우, 공격자에 의해 알려지며 (Django의 고유 한 취약점으로 인해 누출 될 수 있음), 공격자는 문자열을 자신의 세션에 추가합니다. 이 세션은 unpickle 될 때 서버에서 임의의 코드를 실행합니다. 그렇게 하기 위한 기술은 간단하고 인터넷에서 쉽게 이용할 수 있습니다. 쿠키 세션 저장소가 변조를 방지하기 위해 쿠키에 저장된 데이터에 서명하지만 [SECRET_KEY](https://docs.djangoproject.com/en/1.st/:settings/#std:setting-SECRET_KEY) 누출이 즉시 원격 코드 실행 취약점으로 확대됩니다 ((For example, here’s an attack scenario if you use [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) to serialize session data. If you’re using the[signed cookie session backend](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#cookie-session-backend) and [`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY) leak immediately escalates to a remote code execution vulnerability.)) #### 번들 직렬화 (([Bundled serializers](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#bundled-serializers))) ##### class serializers.JSONSerializer [`django.core.signing`](https://docs.djangoproject.com/en/1.11/topics/signing/#module-django.core.signing)의 JSON 시리얼 라이저에 대한 래퍼. 기본 데이터 형식 만 serialize 할 수 있습니다. ((A wrapper around the JSON serializer from[`django.core.signing`](https://docs.djangoproject.com/en/1.11/topics/signing/#module-django.core.signing). Can only serialize basic data types.)) 또한 JSON은 문자열 키만 지원하므로 `request.session`의 문자열이 아닌 키를 사용하면 예상대로 작동하지 않습니다. ((In addition, as JSON supports only string keys, note that using non-string keys in`request.session` won’t work as expected:)) ```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`](https://docs.python.org/3/library/exceptions.html#UnicodeDecodeError)가 발생하는 '\ xd9'\와 같은 UTF8이 아닌 바이트)는 저장할 수 없습니다. ((Similarly, data that can’t be encoded in JSON, such as non-UTF8 bytes like`'\xd9'`\(which raises [`UnicodeDecodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeDecodeError)\), can’t be stored.)) JSON 직렬화의 제한 사항에 대한 자세한 내용은 [자체 시리얼 작성](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers) 섹션을 참조하십시오. ((See the[Write your own serializer](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#custom-serializers) section for more details on limitations of JSON serialization.)) #### class serializers.PickleSerializer 임의의 파이썬 개체를 지원하지만 위에서 설명한대로 [`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY)가 있으면 원격 코드 실행 취약점이 발생할 수 있습니다. )가 공격자에게 알려지게 됩니다. ((Supports arbitrary Python objects, but, as described above, can lead to a remote code execution vulnerability if[`SECRET_KEY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SECRET_KEY)becomes known by an attacker.)) #### Write your own serializer [`PickleSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer)와 달리 [`JSONSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.JSONSerializer) 임의의 파이썬 데이터 유형을 처리 할 수 없습니다. 종종 그렇듯이 편의성과 보안 성 사이에는 트레이드 오프가 있습니다. ((Note that unlike[`PickleSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer), the[`JSONSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.JSONSerializer)cannot handle arbitrary Python data types. As is often the case, there is a trade-off between convenience and security.)) `datetime`과 `Decimal`을 포함한 더 진보 된 데이터 타입을 JSON 지원 세션에 저장하고 싶다면, 커스텀 시리얼 라이저를 작성하거나 (`request.session`에 저장하기 전에 이러한 값을 JSON 직렬화 가능한 객체로 변환해야합니다). 이러한 값을 직렬화하는 것은 매우 간단합니다 ([`DjangoJSONEncoder`](https://docs.djangoproject.com/en/1.11/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder) 도움이 될 수 있습니다. 디코더는 안정적으로 당신이 넣는 것과 똑같은 것을 되 찾을 수 있습니다. ((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`](https://docs.djangoproject.com/en/1.11/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder)may be helpful), writing a decoder that can reliably get back the same thing that you put in is more fragile.)) 예를 들어 `datetime`을 반환 할 위험이 있습니다. 실제로는 `datetime`과 같은 형식으로 된 문자열입니다. ((For example, you run the risk of returning a`datetime` that was actually a string that just happened to be in the same format chosen for`datetime`s.)) serializer 클래스는 세션 데이터의 사전을 직렬화 및 비 직렬화하는 두 가지 메소드, `dumps(self, obj)` 및 `loads(self, data)`를 구현해야 합니다. ((Your serializer class must implement two methods,`dumps(self,obj)` and `loads(self,data)`, to serialize and deserialize the dictionary of session data, respectively.)) ### Session object guidelines - `request.session`에서 사전 파이썬 문자열을 사전 키로 사용하십시오. 이는 어렵고 빠른 규칙보다 관례입니다.(( * Use normal Python strings as dictionary keys on `request.session`. This is more of a convention than a hard-and-fast rule.)) - 밑줄로 시작하는 세션 사전 키는 장고의 내부 용으로 예약되어 있습니다. ((* Session dictionary keys that begin with an underscore are reserved for internal use by Django.)) - `request.session`을 새로운 객체로 오버라이드하지 말고 그 속성에 접근하거나 설정하지 마라. 파이썬 사전처럼 사용하십시오.((* Don’t override `request.session` with a new object, and don’t access or set its attributes. Use it like a Python dictionary.)) ### Examples 이 간단한보기는 사용자가 주석을 게시 한 후 `has_commented` 변수를 `True`로 설정합니다. 사용자가 한 번 이상 주석을 게시 할 수 없습니다. ((This simplistic view sets a`has_commented` variable to `True` after a user posts a comment. It doesn’t let a user post a comment more than once:)) ```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!') ``` 이 간단한보기는 사이트의 "회원"에 로그인합니다. ((This simplistic view logs in a “member” of the site:)) ```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()`에 따라 이 멤버를 로그 아웃합니다: ((…And this one logs a member out, according to `login()` above:)) ```python def logout(request): try: del request.session['member_id'] except KeyError: pass return HttpResponse("You're logged out.") ``` 표준 [`django.contrib.auth.logout ()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout) 함수는 실제로 약간의 기능 을합니다. 부주의한 데이터 유출을 막기 위해 `request()`의 [`flush()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.flush) 메소드를 호출합니다. 세션. 우리는 완전한 `logout()` 구현이 아닌 세션 객체를 다루는 방법을 보여주기 위해이 예제를 사용하고 있습니다. ((The standard [`django.contrib.auth.logout()`](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout)function actually does a bit more than this to prevent inadvertent data leakage. It calls the[`flush()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.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.)) ## 테스트 쿠키 설정 ((Setting test cookies)) 편의상 Django는 사용자의 브라우저가 쿠키를 허용하는지 테스트하는 쉬운 방법을 제공합니다. ((As a convenience, Django provides an easy way to test whether the user’s browser accepts cookies.)) `request.session`의 [`set_test_cookie()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.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)를 호출하십시오. - 동일한 뷰 호출이 아닌 후속 뷰에서 호출합니다. (( Just call the [`set_test_cookie()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_test_cookie)method of `request.session` in a view, and call[`test_cookie_worked()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked)in a subsequent view – not in the same view call. )) 쿠키가 작동하는 방식 때문에 `set_test_cookie ()` 와 `test_cookie_worked ()` 사이의 어색한 분리가 필요합니다. 쿠키를 설정하면 브라우저의 다음 요청이있을 때까지 브라우저가 쿠키를 허용했는지 여부를 실제로 알 수 없습니다. ((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.)) 청소하기 위해 [`delete_test_cookie()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie)를 사용하는 것이 좋습니다. 너 자신 후에. 테스트 쿠키가 작동하는지 확인한 후에이 작업을 수행하십시오. ((It’s good practice to use [`delete_test_cookie()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie)to clean up after yourself. Do this after you’ve verified that the test cookie worked.)) 다음은 일반적인 사용 예입니다. ((Here’s a typical usage example:)) ```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') ``` ## 뷰가 아닌 세션 사용 ((Using sessions out of views)) Note 이 섹션의 예제는 `django.contrib.sessions.backends.db` 백엔드에서 직접 `SessionStore` 객체를 가져옵니다. 자신의 코드에서 [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE)에 의해 지정된 세션 엔진으로부터 `SessionStore`를 가져 오는 것을 고려해야합니다. 아래: ((The examples in this section import the`SessionStore`object directly from the`django.contrib.sessions.backends.db`backend. In your own code, you should consider importing`SessionStore`from the session engine designated by[`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE), as below:)) ```python from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore ``` 뷰 외부에서 세션 데이터를 조작하는 데 사용할 수있는 API는 다음과 같습니다. ((An API is available to manipulate session data outside of a view:)) ```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`가 생성 될 때까지 반복합니다. ((`SessionStore.create()` is designed to create a new session (i.e. one not loaded from the session store and with`session_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 a`session_key`that collides with an existing one. `create()` calls `save()` and loops until an unused `session_key` is generated.)) `django.contrib.sessions.backends.db` 백엔드를 사용한다면, 각 세션은 정상적인 Django 모델 일뿐입니다. `Session` 모델은 `django/contrib/sessions/models.py`에 정의되어 있습니다. 정상적인 모델이기 때문에 일반적인 Django 데이터베이스 API를 사용하여 세션에 액세스 할 수 있습니다. ((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:)) ```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()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.get_decoded)를 다음과 같이 호출해야 합니다. 세션 사전을 얻으십시오. 이는 사전이 인코딩 된 형식으로 저장되기 때문에 필요합니다. ((Note that you’ll need to call [`get_decoded()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.get_decoded)to get the session dictionary. This is necessary because the dictionary is stored in an encoded format:)) ```python s.session_data 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...' s.get_decoded() {'user_id': 42} ``` ## 세션 저장시 ((When sessions are saved)) 기본적으로 Django는 세션이 수정되었을 때, 즉 사전 값이 할당되거나 삭제 된 경우에만 세션 데이터베이스에 저장합니다. ((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:)) ```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` 속성을 설정하여 세션 객체가 명시 적으로 변경되었음을 세션 객체에 알릴 수 있습니다 : ((In the last case of the above example, we can tell the session object explicitly that it has been modified by setting the`modified`attribute on the session object:)) ```python request.session.modified = True ``` 이 기본 동작을 변경하려면 [`SESSION_SAVE_EVERY_REQUEST`](https://docs.djangoproject.com/en/1.st/:ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST) 설정을 'True'으로 설정하십시오. `True`로 설정되면 Django는 매 요청마다 데이터베이스에 세션을 저장합니다. ((To change this default behavior, set the [`SESSION_SAVE_EVERY_REQUEST`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST)setting to `True`. When set to `True`, Django will save the session to the database on every single request.)) 세션 쿠키는 세션이 생성되거나 수정 된 경우에만 전송됩니다. [`SESSION_SAVE_EVERY_REQUEST`](https://docs.djangoproject.com/en/1.st/ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST)가 `True`이면 모든 요청에 세션 쿠키가 전송됩니다. ((Note that the session cookie is only sent when a session has been created or modified. If [`SESSION_SAVE_EVERY_REQUEST`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST) is `True`, the session cookie will be sent on every request.)) 비슷하게, 세션 쿠키의 `expire` 부분은 세션 쿠키가 전송 될 때마다 업데이트됩니다. ((Similarly, the `expires` part of a session cookie is updated each time the session cookie is sent.)) 응답의 상태 코드가 500이면 세션이 저장되지 않습니다. ((The session is not saved if the response’s status code is 500.)) ## 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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE)setting. By default,[`SESSION_EXPIRE_AT_BROWSER_CLOSE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE)is set to`False`, which means session cookies will be stored in users’ browsers for as long as[`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE)is set to`True`, 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()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry)method of`request.session`as described above in[using sessions in views](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-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, the`django_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 the`django_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 does_not_log out, the row never gets deleted. A similar process happens with the file backend. Django does_not_provide 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`](https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-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 few[Django settings](https://docs.djangoproject.com/en/1.11/ref/settings/#settings-sessions)give you control over session behavior: * [`SESSION_CACHE_ALIAS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_CACHE_ALIAS) * [`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_AGE) * [`SESSION_COOKIE_DOMAIN`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_DOMAIN) * [`SESSION_COOKIE_HTTPONLY`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_HTTPONLY) * [`SESSION_COOKIE_NAME`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_NAME) * [`SESSION_COOKIE_PATH`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_PATH) * [`SESSION_COOKIE_SECURE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_SECURE) * [`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE) * [`SESSION_EXPIRE_AT_BROWSER_CLOSE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE) * [`SESSION_FILE_PATH`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_FILE_PATH) * [`SESSION_SAVE_EVERY_REQUEST`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST) * [`SESSION_SERIALIZER`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_SERIALIZER) ## 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 into`good.example.com`and get a valid session for their account. If the attacker has control over`bad.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 visit`good.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 if`good.example.com`sets its[`SESSION_COOKIE_DOMAIN`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_DOMAIN) to`".example.com"`which would cause session cookies from that site to be sent to`bad.example.com`. ## Technical details[¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#technical-details) * The session dictionary accepts any [`json`](https://docs.python.org/3/library/json.html#module-json) serializable value when using [`JSONSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.JSONSerializer) or any picklable Python object when using [`PickleSerializer`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.serializers.PickleSerializer) . See the [`pickle`](https://docs.python.org/3/library/pickle.html#module-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 named`SessionStore`and is located in the module designated by[`SESSION_ENGINE`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_ENGINE). All`SessionStore`classes available in Django inherit from[`SessionBase`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase)and implement data manipulation methods, namely: * `exists()` * `create()` * `save()` * `delete()` * `load()` * [`clear_expired()`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.clear_expired) In order to build a custom session engine or to customize an existing one, you may create a new class inheriting from[`SessionBase`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase)or any other existing`SessionStore`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 \(namely`db`and`cached_db`\) may be done by inheriting[`AbstractBaseSession`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession)and either`SessionStore`class. `AbstractBaseSession`and`BaseSessionManager`are importable from`django.contrib.sessions.base_session`so that they can be imported without including`django.contrib.sessions`in[`INSTALLED_APPS`](https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS). _class_ `base_session.` `AbstractBaseSession` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession) The abstract base session model. `session_key` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.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` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.session_data) A string containing an encoded and serialized session dictionary. `expire_date` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.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`](https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-clearsessions)management command is run. _classmethod_ `get_session_store_class` \(\) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.get_session_store_class) Returns a session store class to be used with this session model. `get_decoded` \(\) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.AbstractBaseSession.get_decoded) Returns decoded session data. Decoding is performed by the session store class. You can also customize the model manager by subclassing[`BaseSessionManager`](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.BaseSessionManager): _class_ `base_session.` `BaseSessionManager` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.BaseSessionManager) `encode` \( _session\_dict_ \) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.BaseSessionManager.encode) 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_ \) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.base_session.BaseSessionManager.save) Saves session data for a provided session key, or deletes the session in case the data is empty. Customization of`SessionStore`classes is achieved by overriding methods and properties described below: _class_ `backends.db.` `SessionStore` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.db.SessionStore) Implements database-backed session store. _classmethod_ `get_model_class` \(\) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.db.SessionStore.get_model_class) Override this method to return a custom session model if you need one. `create_model_instance` \( _data_ \) [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.db.SessionStore.create_model_instance) 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` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.cached_db.SessionStore) Implements cached database-backed session store. `cache_key_prefix` [¶](https://docs.djangoproject.com/en/1.11/topics/http/sessions/#django.contrib.sessions.backends.cached_db.SessionStore.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-in`cached_db`session store to a custom one based on`cached_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. open/django-세션-사용하기.txt 마지막으로 수정됨: 2020/07/15 08:48저자 127.0.0.1