mod_python : 4.8.1 Classes / 俺訳 & 俺メモ

途中。。。。。。。。。

  1. 実際のSessionマネージメントクラスは PythonOption で指定できる。というか指定して使いなさい。
  2. 指定しないと、決定に関してルールがいくつかあるが、DbmSessionが使われることがおおいんじゃないの。
  3. dictのサブクラスで実装されている。
  4. Sessionインスタンスの紐付けは Set-Cookie : pyid=************************************** ; path=/path/to/app でされる
  5. timeoutは1800秒で、コンストラクタで指定可能
  6. lock=1(default)で、atomic
  7. GCは1000回の呼び出しごとに1回ランダムに行われる。req.register_cleanup でGC関数をフック可能。
  8. dbmセッションDBファイルのパスはPythonOptionで指定可能
  9. FileSessionだとセッションごとに1ファイル。httpdを落としても消えない。GCで定期的に削除。PythonOptionで細かくGCの動きを設定。

4.8.1 Classes

Session(
req[, sid, secret, timeout, lock])

Session() takes the same arguments as BaseSession.

This function returns a instance of the default session class. The session class to be used can be specified using PythonOption mod_python.session.session_type value, where value is one of DbmSession, MemorySession or FileSession. Specifying custom session classes using PythonOption session is not yet supported.

If session type option is not found, the function queries the MPM and based on that returns either a new instance of DbmSession or MemorySession. MemorySession will be used if the MPM is threaded and not forked (such is the case on Windows), or if it threaded, forked, but only one process is allowed (the worker MPM can be configured to run this way). In all other cases DbmSession is used.

Note that on Windows if you are using multiple Python interpreter instances and you need sessions to be shared between applications running within the context of the distinct Python interpreter instances, you must specifically indicate that DbmSession should be used, as MemorySession will only allow a session to be valid within the context of the same Python interpreter instance.

Also note that the option name mod_python.session.session_type only started to be used from mod_python 3.3 onwards. If you need to retain compatability with older versions of mod_python, you should use the now obsolete session option instead.

PythonOption    mod_python.session.session_type    "value"  ( mod_python >= 3.3 )

PythonOption    session   "value"  ( mod_python < 3.3 )

class BaseSession(
req[, sid, secret, timeout, lock])

This class is meant to be used as a base class for other classes that implement a session storage mechanism. req is a required reference to a mod_python request object.

BaseSession is a subclass of dict. Data can be stored and retrieved from the session by using it as a dictionary.

( dictのサブクラス )

sid is an optional session id; if provided, such a session must already exist, otherwise it is ignored and a new session with a new sid is created. If sid is not provided, the object will attempt to look at cookies for session id. If a sid is found in cookies, but it is not previously known or the session has expired, then a new sid is created. Whether a session is “new” can be determined by calling the is_new() method.

Cookies generated by sessions will have a path attribute which is calculated by comparing the server DocumentRoot and the directory in which the PythonHandler directive currently in effect was specified. E.g. if document root is /a/b/c and the directory PythonHandler was specified was /a/b/c/d/e, the path will be set to /d/e.

The deduction of the path in this way will only work though where the Directory directive is used and the directory is actually within the document root. If the Location directive is used or the directory is outside of the document root, the path will be set to /. You can force a specific path by setting the mod_python.session.application_path option ("PythonOption mod_python.session.application_path /my/path" in server configuration).

Note that prior to mod_python 3.3, the option was ApplicationPath. If your system needs to be compatible with older versions of mod_python, you should continue to use the now obsolete option name.

The domain of a cookie is by default not set for a session and as such the session is only valid for the host which generated it. In order to have a session which spans across common sub domains, you can specify the parent domain using the mod_python.session.application_domain option ("PythonOption mod_python.session.application_domain mod_python.org" in server configuration).

When a secret is provided, BaseSession will use SignedCookie when generating cookies thereby making the session id almost impossible to fake. The default is to use plain Cookie (though even if not signed, the session id is generated to be very difficult to guess).

A session will timeout if it has not been accessed and a save performed, within the timeout period. Upon a save occuring the time of last access is updated and the period until the session will timeout be reset. The default timeout period is 30 minutes. An attempt to load an expired session will result in a “new” session.

The lock argument (defaults to 1) indicates whether locking should be used. When locking is on, only one session object with a particular session id can be instantiated at a time.

A session is in “new” state when the session id was just generated, as opposed to being passed in via cookies or the sid argument.

is_new(
)

Returns 1 if this session is new. A session will also be “new” after an attempt to instantiate an expired or non-existent session. It is important to use this method to test whether an attempt to instantiate a session has succeeded, e.g.:
sess = Session(req)
if sess.is_new():
    # redirect to login
    util.redirect(req, 'http://www.mysite.com/login')

id(
)

Returns the session id.

created(
)

Returns the session creation time in seconds since beginning of epoch.

last_accessed(
)

Returns last access time in seconds since beginning of epoch.

timeout(
)

Returns session timeout interval in seconds.

set_timeout(
secs)

Set timeout to secs.

invalidate(
)

This method will remove the session from the persistent store and also place a header in outgoing headers to invalidate the session id cookie.

load(
)

Load the session values from storage.

save(
)

This method writes session values to storage.

delete(
)

Remove the session from storage.

init_lock(
)

This method initializes the session lock. There is no need to ever call this method, it is intended for subclasses that wish to use an alternative locking mechanism.

lock(
)

Locks this session. If the session is already locked by another thread/process, wait until that lock is released. There is no need to call this method if locking is handled automatically (default).

This method registeres a cleanup which always unlocks the session at the end of the request processing.

unlock(
)

Unlocks this session. (Same as lock() – when locking is handled automatically (default), there is no need to call this method).

cleanup(
)

This method is for subclasses to implement session storage cleaning mechanism (i.e. deleting expired sessions, etc.). It will be called at random, the chance of it being called is controlled by CLEANUP_CHANCE Session module variable (default 1000). This means that cleanups will be ordered at random and there is 1 in 1000 chance of it happening. Subclasses implementing this method should not perform the (potentially time consuming) cleanup operation in this method, but should instead use req.register_cleanup to register a cleanup which will be executed after the request has been processed.

class DbmSession(
req, [, dbm, sid, secret, dbmtype, timeout, lock])

This class provides session storage using a dbm file. Generally, dbm access is very fast, and most dbm implementations memory-map files for faster access, which makes their performance nearly as fast as direct shared memory access.

dbm is the name of the dbm file (the file must be writable by the httpd process). This file is not deleted when the server process is stopped (a nice side benefit of this is that sessions can survive server restarts). By default the session information is stored in a dbmfile named mp_sess.dbm and stored in a temporary directory returned by tempfile.gettempdir() standard library function. An alternative directory can be specified using PythonOption mod_python.dbm_session.database_directory /path/to/directory. The path and filename can can be overridden by setting PythonOption mod_python.dbm_session.database_filename filename.

Note that the above names for the PythonOption settings were changed to these values in mod_python 3.3. If you need to retain compatability with older versions of mod_python, you should continue to use the now obsolete session_directory and session_dbm options.

The implementation uses Python anydbm module, which will default to dbhash on most systems. If you need to use a specific dbm implementation (e.g. gdbm), you can pass that module as dbmtype.

Note that using this class directly is not cross-platform. For best compatibility across platforms, always use the Session() function to create sessions.

class FileSession(
req, [, sid, secret, timeout, lock, fast_cleanup, verify_cleanup])

New in version 3.2.0.

This class provides session storage using a separate file for each session. It is a subclass of BaseSession.

Session data is stored in a separate file for each session. These files are not deleted when the server process is stopped, so sessions are persistent across server restarts. The session files are saved in a directory named mp_sess in the temporary directory returned by the tempfile.gettempdir() standard library function. An alternate path can be set using PythonOption mod_python.file_session.database_directory /path/to/directory. This directory must exist and be readable and writeable by the apache process.

Note that the above name for the PythonOption setting was changed to these values in mod_python 3.3. If you need to retain compatability with older versions of mod_python, you should continue to use the now obsolete session_directory option.

Expired session files are periodically removed by the cleanup mechanism. The behaviour of the cleanup can be controlled using the fast_cleanup and verify_cleanup parameters, as well as PythonOption mod_python.file_session.cleanup_time_limit and PythonOption mod_python.file_session.cleanup_grace_period.

  • fast_cleanup A boolean value used to turn on FileSession cleanup optimization. Default is True and will result in reduced cleanup time when there are a large number of session files.

    When fast_cleanup is True, the modification time for the session file is used to determine if it is a candidate for deletion. If (current_time - file_modification_time) > (timeout + grace_period), the file will be a candidate for deletion. If verify_cleanup is False, no futher checks will be made and the file will be deleted.

    If fast_cleanup is False, the session file will unpickled and it’s timeout value used to determine if the session is a candidate for deletion. fast_cleanup = False implies verify_cleanup = True.

    The timeout used in the fast_cleanup calculation is same as the timeout for the session in the current request running the filesession_cleanup. If your session objects are not using the same timeout, or you are manually setting the timeout for a particular session with set_timeout(), you will need to set verify_cleanup = True.

    The value of fast_cleanup can also be set using PythonOption mod_python.file_session.enable_fast_cleanup.

  • verify_cleanup Boolean value used to optimize the FileSession cleanup process. Default is True.

    If verify_cleanup is True, the session file which is being considered for deletion will be unpickled and its timeout value will be used to decide if the file should be deleted.

    When verify_cleanup is False, the timeout value for the current session will be used in to determine if the session has expired. In this case, the session data will not be read from disk, which can lead to a substantial performance improvement when there are a large number of session files, or where each session is saving a large amount of data. However this may result in valid sessions being deleted if all the sessions are not using a the same timeout value.

    The value of verify_cleanup can also be set using PythonOption mod_python.file_session.verify_session_timeout.

  • PythonOption mod_python.file_session.cleanup_time_limit [value] Integer value in seconds. Default is 2 seconds.

    Session cleanup could potentially take a long time and be both cpu and disk intensive, depending on the number of session files and if each file needs to be read to verify the timeout value. To avoid overloading the server, each time filesession_cleanup is called it will run for a maximum of session_cleanup_time_limit seconds. Each cleanup call will resume from where the previous call left off so all session files will eventually be checked.

    Setting session_cleanup_time_limit to 0 will disable this feature and filesession_cleanup will run to completion each time it is called.

  • PythonOption mod_python.file_session.cleanup_grace_period [value] Integer value in seconds. Default is 240 seconds. This value is added to the session timeout in determining if a session file should be deleted.

    There is a small chance that a the cleanup for a given session file may occur at the exact time that the session is being accessed by another request. It is possible under certain circumstances for that session file to be saved in the other request only to be immediately deleted by the cleanup. To avoid this race condition, a session is allowed a grace_period before it is considered for deletion by the cleanup. As long as the grace_period is longer that the time it takes to complete the request (which should normally be less than 1 second), the session will not be mistakenly deleted by the cleanup.

    The default value should be sufficient for most applications.

class MemorySession(
req, [, sid, secret, timeout, lock])

This class provides session storage using a global dictionary. This class provides by far the best performance, but cannot be used in a multi-process configuration, and also consumes memory for every active session. It also cannot be used where multiple Python interpreters are used within the one Apache process and it is necessary to share sessions between applications running in the distinct interpreters.

Note that using this class directly is not cross-platform. For best compatibility across platforms, always use the Session() function to create sessions.

4.8.1 Classes

カテゴリー: 未分類 パーマリンク

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中