Mod_python ドキュメント¶
注釈
この和訳は,菊地時夫氏、吉田勝彦氏の手で翻訳された「Mod_python Manual Release 3.1.3」をもとに、 Python ドキュメント和訳プロジェクトが改訳を行ったものです. いまお読みのバージョンは、reST への移植と、バージョン 3.5 の対応を行っています。
このドキュメントは、 mod_python に関する必須で信頼できる情報源であるとともに、網羅的なリファレンスとしても使えて、ユーザガイドやチュートリアルも兼ねるよう目指しています。
参考
- プログラミング言語 Python のサイト
- プログラミング言語 Python の情報です。
- Apache HTTP サーバプロジェクトのサイト
- Apache Web サーバの情報です。
はじめに¶
パフォーマンス¶
を使う大きな利点の一つは、従来の CGI に対する大幅な速度向上です。
以下に示すのはかなり大雑把なテストの結果です。
このテストは、 Red Had Linux 7.3 の動作している 1.2 GHz の Pentium マシン上で行いました。
4 種類のスクリプトは Ab で呼び出し、いずれのスクリプトも標準モジュールの cgi を import しています (通常の Python CGI スクリプトは、みな cgi の import で始めるからです)。
その後、 Hello!
を出力させています。
結果は、並列度 1 で、10000 回のリクエストを処理させたときの値です:
Standard CGI: 23 requests/s
Mod_python cgihandler: 385 requests/s
Mod_python publisher: 476 requests/s
Mod_python handler: 1203 requests/s
Apache HTTP サーバ API¶
Apache は、リクエストの処理を、リクエストの読み出し,ヘッダの解析,アクセス権限の チェックといった フェイズ に分割します。 各フェイズは ハンドラ (handler) と呼ばれる関数で実装できます。 従来,ハンドラは C で書かかれ Apache モジュールの形にコンパイルされていました。 これに対して, mod_python は Python で Apache ハンドラを書いて,Apache の機能を拡張できます。 Apache のリクエスト処理過程についての詳しい情報は、 Apache Developer Documentation や、 Mod_python - Integrating Python with Apache を参照してください.
今のところ、 mod_python では、Apache HTTP サーバ API の一部だけしかアクセスできません。 このプロジェクトのゴールは、API を100% カバーすることではありません。 それよりも、 API の最も便利な部分や、API をより「Python的に」使う方法にフォーカスしています。
その他の機能¶
Mod_python は、 Web 開発の領域の様々な機能を提供しています。 HTML に Python を埋め込んで実行するためのパーザ(psp – Python Server Pager)、URL 空間をモジュールや関数のマップするためのハンドラ (Publisher ハンドラ)、セッションのサポート (Session – Session Management)、クッキー操作などです。
参考
- Apache HTTP Server Developer Documentation
- HTTP 開発者向けの情報です。
- Mod_python - Integrating Python with Apache
- mod_python と Apache HTTP Server のインタフェースに関する情報です。
インストール¶
注釈
インストールやその他の問題に関して、参考になるのは依然として mod_python メーリングリストです。 表題にsubscribe と書いたメールを mod_python mod_python-request@modpython.org に送るか、 mod_python メーリングリストのページ に行ってみましょう。
インストール要件¶
理想的なケースでは、 OS がパッケージ済みの mod_python を提供しています。 そうでなければ、自分でコンパイルせねばなりません。 このバージョンの mod_python には、下記が必要です:
- Python 2 (2.6 以降) または Python 3 (3.3 以降)
- Apache 2.2 以降。 Apache 2.4 を強く推奨します。
mod_python をコンパイルするには、Apache と Python の両方の include ファイルと、Python のライブラリが、システムにインストールされていなければなりません。 Python と Apache をソースコードからインストールしたなら、必要なものはすべて揃っているはずです。 しかし、パッケージ済みのソフトウェアを使っている場合には、 mod_python のコンパイルに必要な include ファイルやライブラリの入った開発者向けのパッケージを追加で入れる必要があるでしょう。 詳しくは、 OS のドキュメントを調べてみてください。 (ヒント: python-devel や python-dev, apache-devel, apache-dev, httpd-dev といったパッケージを探してみてください)
コンパイル¶
./configure
を実行する¶
./configure
スクリプトを実行すると、実行環境を解析して、使っているシステムに特化した専用の Makefile を作成します。
autoconf が実行する標準のオプション以外に、 ./configure
には以下のオプションがあります:
- apxs というプログラムを利用できるか調べます。
apxs は標準の Apache 配布物に入っていて、コンパイルに必要です。
apxs の場所は、以下のように、
with-apxs
オプションでマニュアル指定もできます:$ ./configure --with-apxs=/usr/local/apache/bin/apxsこのオプションはいつも指定するよう勧めます。
Python のバージョンを調べ、Pythonバイナリ中にコンパイルされている様々なパラメタから、
libpython
がどこにあるか判定を試みます。 デフォルトではPATH
中に見付かった python を使います。パス上で最初に見付かる Python バイナリが mod_python の実行にふさわしくないバージョンだったり、他のバージョンのPythonを使いたい場合には、以下の例のように
with-python
を指定して、別の Python の在処を指定できます:$ ./configure --with-python=/usr/local/bin/python2.3
Apache の排他制御ロック用のディレクトリを設定します (APR の選んだ排他制御メカニズムがロックディレクトリを必要とする場合)。
排他制御ロックを使うのは、 mod_python の Sessions と PSP (内部で Session を維持しているため) だけです。 mod_python の Session や PSP を使わないのなら、この設定は関係ありません。
デフォルトの場所は
/tmp
です。ディレクトリは実在せねばならず、Apache プロセスのオーナ権限で書き込めなければなりません。with-mutex-dir
オプションを使って、以下のように指定します:$ ./configure --with-mutex-dir=/var/run/mod_python
排他制御ディレクトリは、実行時に PythonOption
mod_python.mutex_directory
で指定できます。 Apache の設定 を参照してください。New in version 3.3.0
mod_python が確保する排他制御ロックの最大数を指定します。
排他制御ロックを使うのは、 mod_python の Sessions と PSP (内部で Session を維持しているため) だけです。 mod_python の Session や PSP を使わないのなら、この設定は関係ありません。
システムによっては、ロックに使える mutex リソースが限られています。 この値を増やすと、セッションのロック時のパフォーマンスが向上することがあります。 デフォルトは 8 です。高いパフォーマンスが必要なら、 32 程度が合理的です。
with-max-locks
オプションは以下のように指定します:$ ./configure --with-max-locks=32
ロックの数は、実行時に PythonOption
mod_python.mutex_locks
で指定できます。 Apache の設定 を参照してください。New in version 3.2.0
flex を指定して、バージョンを固定します。 flex が
PATH
上にない場合、 configure は失敗します。 また、正しくないバージョンがあると、 configure は警告を出力します。src/psp_parser.c
を作りなおす必要がなければ、警告メッセージは無視してかまいません。このパーザは、PSPが使います(psp – Python Server Pager 参照)。 パーザは C で書かれていて、 flex を使っています。 (リエントラントバージョンの flex 2.5.31 以降が必要です)
パス上で最初に見つかる flex がコンパイルに適していない場合や、使いたくないバージョンである場合には、以下のようにして
with-flex
を指定してください:$ ./configure --with-flex=/usr/local/bin/flex
New in version 3.2.0
Running make
¶
To start the build process, simply run:
$ make
Installing¶
make install
を実行します。
インストール作業のこの部分は root で行う必要があります:
$ sudo make install
- このコマンドは、ライブラリ (
mod_python.so
) を、Apache のすべてのモジュールが入るlibexec
ディレクトリにコピーします。 - 次に、Python ライブラリを
site-packages
にコピーし、コンパイルします。
- このコマンドは、ライブラリ (
注釈
Pythonライブラリだけ、あるいは DSO (mod_python.so) だけを選択的にインストールしたい場合には (この場合、常にスーパユーザ権限が必要なわけではありません)、 make のターゲットに install_py_lib
や install_dso
を使ってください。
Apache の設定¶
LoadModule
Apacheの設定ファイルに以下の設定行を追加して、モジュールをロードするよう指示する必要があります。 設定ファイルは通常、
httpd.conf
またはapache.conf
という名前です::oLoadModule python_module libexec/mod_python.so
mod_python.so の実際のパスは場合によって異なりますが、 make install を行うと、 mod_python.so がどこに置かれたか、そして
LoadModule
ディレクトリをどう書けばよいかを報告してくれます。テスト を読んで、基本的な設定パラメタを確認してください。
テスト¶
手元のウェブサイトから見えるディレクトリ、例えば
htdocs/test
を作成してください。下記のApache ディレクティブを、メインのサーバ設定ファイルに追加します:
<Directory /some/directory/htdocs/test> AddHandler mod_python .py PythonHandler mptest PythonDebug On </Directory>
(上の
/some/directory
は、お使いのシステムに合わせて変えてください。通常は Apache の ServerRoot の設定値と同じです)この設定は、
.htaccess
ファイルにも書けます。.htaccess
ファイルは、デフォルトの設定では無効になっているため、このディレクトリに、少なくともFileInfo
の設定されたAllowOverride
を適用しておかねばなりません。上の設定によって、
.py
で終わる URL は mod_python で処理されるようになりました。 リクエスト処理が mod_python に渡ると、 mod_python は適切な python ハンドラ を探して処理します。 ここでは、PythonHandler
ディレクティブはmptest
を Python ハンドラとして指定しています。 Python ハンドラがどのように定義されているかは、後でわかります。ここまでの作業でメインの設定ファイルに変更を加えているならば、変更内容を有効にするため、Apacheを再起動する必要があります。
htdocs/test
ディレクトリ下のmptest.py
ファイルを編集して、以下の内容にします (ブラウザからカット&ペーストするときには注意しましょう。インデントが正しくなかったり、文法エラーになったりするかもしれません):from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") return apache.OK
mptest.py
が参照先になるように、ブラウザに URL を指定します。'Hello World!'
という文字列を読めるはずです。 うまく読めなければ、次のトラブルシューティングの節を参照してください。上で行った設定のため、
test
ディレクトリ中の .py で終わるファイル名なら 何でも ブラウザに指定できるので注意してください。 たとえば/test/foobar.py
に行っても、mptest.py
と全く同じ動作になります。 これは、ハンドラの実装が、今扱っている URL が何であるかに関係なく、同じ処理をしているからです。全てうまく動作しているなら、 チュートリアル に進みましょう。
トラブルシューティング¶
問題の原因を調べるためにできることが 2, 3 あります:
エラー出力が出ていれば、注意深く調べます。
サーバのエラーログファイルを調べます。エラーログファイルには、有用な手がかりが記録されていることがあります。
Apache を、コマンドラインから単一プロセスモード (single process mode) で起動してみましょう:
./httpd -X
この起動方法は Apache がバックグラウンドで動作するのを防ぐので、有用な情報を得られることがあります。
mod_python 3.2.0 からは、 mod_python.testhandler で設定ファイルを診断できます。
httpd.conf
に下記を追加してください:<Location /mpinfo> SetHandler mod_python PythonHandler mod_python.testhandler </Location>
ブラウザで
/mpinfo
(例:http://localhost/mpinfo
) にアクセスすると、設定情報を表示します。 この情報は、何か問題をメーリングリストに報告するときに役に立ちます。メーリングリスト で質問してみましょう。 質問するときには、以下のスペックを載せるようにしてください:
- mod_python のバージョン。
- OS のタイプ、名前とバージョン。
- Python のバージョンと、コンパイル時に特別に指定したオプション。
- Apache のバージョン。
- Apache 設定ファイルや
.htaccess
中の関連する部分。 - Python コードの関連する部分。
チュートリアル¶
で、どうやったらちゃんと動くんですか?
この節は、インストールが終わって、mod_python プログラミングを始めてみる人のためのガイドです。 インストールマニュアルではないので注意してください。
この章を読んだら、 Python API の節の、すくなくとも冒頭の部分にも目を通しておきましょう。
section{publisher ハンドラを使ってみるlabel{tut-pub}}
publisher ハンドラを使ってみる¶
この節では、詳しいことはさておいて、 mod_python を使い始めてみたい人のために、 publisher ハンドラの概要を簡単に説明します。 mod_python ハンドラの動作の仕組みや、ハンドラとは一体何なのか、といった話題は、チュートリアルの後の節で詳しく説明します。
Publisher ハンドラ は、 mod_python の標準ハンドラの一つです。 このハンドラを使うには、設定ファイルに以下のように書きます:
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
以下の例は、フィードバックを送信する簡単なフォームです。
このフォームは、名前、電子メールアドレス、そしてコメントをユーザに入力させ、その情報を使ってウェブ管理者にメッセージを送ります。
この簡単なアプリは、二つのファイル: データを集めるためのフォームの「 form.html
」と、
フォームのアクションターゲットの「 form.py
」からなります。
フォームの HTML ソースを以下に示します:
Here is the html for the form:
<html>
フィードバックを入力して送ってください:
Please provide feedback below:
<p>
<form action="form.py/email" method="POST">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Comment: <textarea name="comment" rows=4 cols=20></textarea><br>
<input type="submit">
</form>
</html>
<form>
タグの action
要素は form.py/email
を指しています。
次に、以下のような内容で form.py
という名前のファイルを作成します:
# coding: utf-8
import smtplib
from email.MIMEText import MIMEText
WEBMASTER = "webmaster" # webmaster e-mail
SMTP_SERVER = "localhost" # your SMTP server
def email(req, name, email, comment):
# ユーザが全ての情報を入力したか確かめる
if not (name and email and comment):
return u"必要な情報が入力されていません。戻って正しく入力してください。"
# メッセージテキストを作成する
msg = u"""\
コメントを送ります:
%s
敬具
%s
""" % (email, WEBMASTER, comment, name)
# 送信する
mime_msg = MIMEText(msg.encode('utf-8'), 'plain', 'UTF-8')
mime_msg['From'] = email
mime_msg['MIME-Version'] = '1.0'
mime_msg['Subject'] = 'feedback'
mime_msg['Content-Type'] = 'text/html; charset=utf-8'
mime_msg['Content-Transfer-Encoding'] = 'quoted-printable'
conn = smtplib.SMTP(SMTP_SERVER)
conn.sendmail(email, [WEBMASTER], str(mime_msg))
conn.quit()
# ユーザにフィードバックの内容を返す
s = u"""\
<html>
%s さん<br>
コメントありがとうございました。すぐにお返事いたします。
</html>""" % (name)
return s
ユーザが「送信 (Submit)」ボタンを押すと、publisher ハンドラはフォームの各フィールドの情報をキーワード引数にして、 form
モジュール内の関数 email()
を呼び出します。
その際、リクエストオブジェクトを req
引数で渡します。
必要がなければ、 req
を渡す必要はありません。
publisher ハンドラは賢いので、関数が受け取れる引数だけを渡します。
データは関数の戻り値を介してブラウザに戻されます。
publisher ハンドラは、 mod_python を使ったプログラミングをとても簡単にしながらも、リクエストオブジェクトにアクセスできるので、 mod_python の力を余すところなく使えます。
同じようなことは、「ネイティブの」mod_python ハンドラでもできます。
例えば、 req.headers_out
でヘッダをカスタマイズしたり、 apache.SERVER_ERROR
例外を送出してエラーを返したり、 req.write()
や req.read()
を使って、クライアントに対して直接データを読み書きしたりできます。
publisher ハンドラの詳しい情報は Publisher ハンドラ の節を参照してください。
Apache によるリクエスト処理の概要¶
Apache は、リクエストを複数の フェイズ で処理します。 例えば、最初のフェイズではユーザを認証し、次のフェイズではユーザが特定のファイルを閲覧する許可を有しているか調べ、続いて (次のフェイズで) ファイルを読み出してクライアントに送信する、といった具合です。 典型的な静的ファイルのリクエスト処理では、 (1) 要求された URI を実際のファイルの場所に変換する、 (2) ファイルを読み出してクライアントに送信する、 (3) リクエストをログに記録する、という三つのフェイズがあります。 厳密にどのフェイズがどのように処理されるかは、設定によって大きく変わります。
ハンドラ (handler) は、一つのフェイズを処理する関数です。 ある特定のフェイズの処理に対して、複数のハンドラを利用できることもあり、その場合、 Apache は各ハンドラを順番に呼び出します。 各フェイズに対して、まず、Apache の標準のハンドラを呼び出します (ほとんどは、デフォルトの設定hでは極めて基本的な処理しかしないか、あるいは何も行いません)。続いて、 mod_python のような Apache モジュールが提供している追加のハンドラを呼び出します。
mod_python は、Apache で使える全てのハンドラを提供しています。
各々のハンドラは、設定ディレクティブで特に設定しない限り、何も実行しません。
mod_python の設定ディレクティブは PythonAuthenHandler
のように、 Python
で始まって Handler
で終わる名前で、一つのハンドラを一つの Python の関数に対応させます。
つまり、mod_python の主な機能は、みなさんのような開発者が書いた Python の関数と、Apache のハンドラと間を取り持つディスパッチャの働きをすることにあります。
もっともよく使うハンドラは PythonHandler
です。
このハンドラは、実際のコンテンツを提供する際の、リクエストのフェイズを処理します。
このフェイズには名前がないので、 汎用 (generic) ハンドラと呼ばれることがあります。
このハンドラの Apache のデフォルトの動作は、ファイルの読み込みとクライアントへの送信です。
読者のみなさんがアプリを書く場合、たいていはこのハンドラをオーバライドすることになるでしょう。
どんなハンドラを利用できるのか知りたければ、 directives の節を参照してください。
mod_python は実際何をやっているのか¶
仮に、以下のように設定しているとしましょう:
<Directory /mywebdir>
AddHandler mod_python .py
PythonHandler myscript
PythonDebug On
</Directory>
注意: ここでは、 /mywebdir
は物理的な絶対パスです。
- さらに、以下のような内容の Python プログラムが
/mywebdir/myscript.py
にあるとします (Windows ユーザは、ファイル名のスラッシュをバックスラッシュに置き換えてください):
from mod_python import apache def handler(req): req.content_type = "text/plain" req.write("Hello World!") return apache.OK
すると,こんなことが起きます: まず、 AddHandler
ディレクティブは、
Apache に、 /mywebdir
とそれ以下のディレクトリにある .py
で終わる全てのファイルへのリクエストを、全て mod_python で処理するよう指示します。
PythonHandler myscript
ディレクティブは、 mod_python の汎用ハンドラに myscript を使ってリクエストを処理するよう指示します。
PythonDebug On
ディレクティブは、 Python のエラーが発生した場合に、エラー出力を (ログへの記録に加えて) クライアントに送信するよう mod_python に指示します。
開発中には、この機能はとても便利です。
さて、リクエストが送られてくると、Apache は mod_python のハンドラを呼び出してリクエスト処理フェイズを開始します。
mod_python のハンドラは、設定の中から、呼びだされたハンドラに関するディレクティブをチェックして、定義されているハンドラを探します (mod_python はディスパッチャのように働くことを思い出してください)。
ここで示した例題では、generic ハンドラ以外で、mod_python がするべきことは何もありません。
generic ハンドラの番になると、mod_python は PythonHandler myscript
ディレクティブがあることに気づき、以下のような処理を行います:
PythonHandler
sys.path
に追加されていなければ追加します。
PythonHandler
ディレクティブの定義されているディレクトリを、sys.path
の先頭に (まだ付加していなければ) 付加します。myscript
という名前のモジュールを import しようと試みます。 (myscript
が、PythonHandler
ディレクティブの指定されているディレクトリの直下ではなく、サブディレクトリにある場合、import はうまくいかないので注意してください。 サブディレクトリがsys.path
に入っていないからです。PythonHandler subdir.myscript
のように、パッケージ表記を使えば、この問題を回避できます。)myscript
モジュール中から関数handler
を探します。リクエストオブジェクトを渡して
handler
を呼び出します (リクエストオブジェクトについては、後で詳しく述べます)。この時点で、処理はスクリプトの中に移ります。スクリプトを一行づつ見ていきましょう:
from mod_python import apache
この行で、Apache へのインタフェースを提供している apache モジュールを
- import します。
- ごく少数の例外を除いて、mod_python のプログラムには、だいたいこの行があるはずです。
def handler(req):
ハンドラ (handler) 関数の宣言です。 mod_python は、ディレクティブ名を小文字表記にして、先頭の
python
を取り除いた名前をハンドラ名に使うので、PythonHandler
はhandler
という名前になるのです。 ハンドラ関数は別の名前にもできます。その場合は、ディレクティブで::
を使って明示します。 例えば、ハンドラがspam
という関数だったなら、ディレクティブはPythonHandler myscript::spam
になったでしょう。ハンドラは Request Object という引数を取らねばなりません。 リクエストオブジェクトとは、例えばクライアントの IP アドレス、ヘッダ、 URI といった、あるリクエストに関する全ての情報の入ったオブジェクトです。 クライアントへの返信も request オブジェクトを介して行います。 つまり、「応答オブジェクト (response object)」はありません。
req.content_type = "text/plain"
この行では、コンテンツタイプを
text/plain
に設定しています。 デフォルトの設定はtext/html
ですが、この例のハンドラが生成するのは HTMLではなく、text/plain
の方がふさわしいからです。 コンテンツタイプの設定は、必ず'req.write'
を呼ぶ 前に 行ってください。 先に'req.write'
を呼び出してしまうと、クライアントにレスポンス HTTP ヘッダが送信されてしまい、後でコンテンツタイプ (や、他のヘッダ) を変更しても、何の効果もありません。req.write("Hello World!")
文字列``Hello World!`` をクライアントに送信します。.
return apache.OK
全ての処理がうまくいき、リクエストの処理を終えたことを Apache に伝えます。 処理がうまく行かなかった場合には、この行で
apache.HTTP_INTERNAL_SERVER_ERROR
やapache.HTTP_FORBIDDEN
を返すことになります。 処理がうまく行かなかった場合、 Apache はエラーをログに記録して、クライアント向けのエラーメッセージを生成します。
注釈
大事なのは、ハンドラコードを実行するために、必ずしも URL で myscript.py
を参照しなくてもよいということです。
必要なのは、 URL に .py
が入っていることだけです。
AddHandler mod_python .py
は、 mod_python に対して、特定のファイルではなく、 (.py
という拡張子の) ファイルタイプ に対するアクセスを、ハンドラで処理するよう指示しています。
そのため、 URL でどんなファイル名を指定するかは関係なく、ファイルが存在している必要すらないのです。
この設定の下では、 http://myserver/mywebdir/myscript.py
も http://myserver/mywebdir/montypython.py
も、全く同じ結果を返します。
今度はもっと複雑なものを - 認証¶
基本的なハンドラの書き方を理解したところで、もう少し複雑なものに取り組んでみましょう。
ディレクトリをパスワードで保護したいとしましょう。ログイン名は spam
、パスワードは eggs
にします。
まず、認証が必要な場合には、 認証 (authentication) ハンドラを呼び出すようApache に伝えておく必要があります。
設定には、 PythonAuthenHandler
を使います。
設定ファイルは以下のようになります:
<Directory /mywebdir>
AddHandler mod_python .py
PythonHandler myscript
PythonAuthenHandler myscript
PythonDebug On
</Directory>
二つのハンドラの指定が、同じスクリプトを指しています。 これでかまいません。というのも、ご存知のように、mod_python は異なるハンドラに対して異なる名前の関数をスクリプトから探し出すからです。
次に、Basic HTTP 認証を使って、有効なユーザだけを許可するよう、Apache に指示 します (かなり基本的な Apache の設定なので、ここでは詳しく説明しません)。 設定ファイルは以下のようになりました:
<Directory /mywebdir>
AddHandler mod_python .py
PythonHandler myscript
PythonAuthenHandler myscript
PythonDebug On
AuthType Basic
AuthName "Restricted Area"
require valid-user
</Directory>
Apache のバージョンによっては、 AuthAuthoritative
や AuthBasicAuthoritative
ディレクティブを Off
にして、 Basic 認証の処理が mod_python のハンドラに回ってくるようにせねばなりません。
さて、今度は myscript.py
に認証のハンドラを書きましょう。
認証ハンドラは以下のようになります:
from mod_python import apache
def authenhandler(req):
pw = req.get_basic_auth_pw()
user = req.user
if user == "spam" and pw == "eggs":
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
一行づつ見てゆきましょう:
def authenhandler(req):
ハンドラ関数の宣言です。 上でも説明したように、mod_python は、ディレクティブの名前 (
PythonAuthenHandler
)から先頭のPython
を落とし、小文字にした文字列を関数名にするので、関数名はauthenhandler
です。pw = req.get_basic_auth_pw()
これで、パスワードを取得します。 Basic HTTP 認証は、パスワードを base64 エンコード形式で、ほんのちょっとだけ分かりにくくして伝送します。 この関数は、パスワードをデコードして、文字列にして返します。 この関数はユーザ名を取得する前に呼び出さねばなりません。
user = req.user
ユーザが入力したユーザ名を取得します。
if user == "spam" and pw == "eggs": return apache.OK
ユーザが入力した値を比較し、期待通りの値なら、
apache.OK
を返して、Apache に処理を先に進めさせます。 Apache は、このリクエストのフェイズが完了したものとみなし、次のフェイズに進みます。 (.py
ファイルに対するリクエストなら、次はhandler()
を呼び出します。)else: return apache.HTTP_UNAUTHORIZED
期待通りの値でなければ、Apache に
HTTP_UNAUTHORIZED
を返させます。 この戻り値を受け取ったブラウザは、通常、ユーザ名とパスワードの入力を促すダイアログボックスを表示します。
404 ハンドラを自作する¶
場合によっては、 HTTP 404 (HTTP_NOT_FOUND
) や、HTTP 200 以外の結果を返したいことがあります。
これにはちょっとしたトリックが必要です。
ハンドラが HTTP_NOT_FOUND
を返すと、 Apache はエラーページをレンダリングして返します。
そのため、自分のハンドラで自作のエラーページを返したいとなると、問題が発生します。
そこで、 req.status = apache.HTTP_NOT_FOUND
をセットしてページをレンダリングし、 return(apache.OK)
を返してください:
from mod_python import apache
def handler(req):
if req.filename[-17:] == 'apache-error.html':
# エラーを Apache に伝えて、エラーページを出力させる
return(apache.HTTP_NOT_FOUND)
if req.filename[-18:] == 'handler-error.html':
# 自作のエラーページを出力する
req.status = apache.HTTP_NOT_FOUND
pagebuffer = '存在しないページか、どこかに移動してしまったページです。'
else:
# ファイルコンテンツを生成する
pagebuffer = open(req.filename, 'r').read()
# 上の3つのケースのうち後者2つのためのフォールスルー
req.write(pagebuffer)
return(apache.OK)
レスポンスハンドラ以外のフェーズでエラーページを生成して返したい時は、 apache.OK
の代わりに、 apache.DONE
を返さねばなりません。
そうしないと、後続のハンドラフェーズが実行されてしまうからです。
apache.DONE
は、リクエストの処理を直ちに停止させます。
レスポンスハンドラを複数積み重ねて使っている場合も、同じフェーズに登録されている後続のハンドラを実行させたくない場合は、必要に応じて apache.DONE
を使ってください。
Python API¶
Multiple Interpreters¶
When working with mod_python, it is important to be aware of a feature of Python that is normally not used when using the language for writing scripts to be run from command line. (In fact, this feature is not available from within Python itself and can only be accessed through the C language API.) Python C API provides the ability to create subinterpreters. A more detailed description of a subinterpreter is given in the documentation for the Py_NewInterpreter() function. For this discussion, it will suffice to say that each subinterpreter has its own separate namespace, not accessible from other subinterpreters. Subinterpreters are very useful to make sure that separate programs running under the same Apache server do not interfere with one another.
At server start-up or mod_python initialization time, mod_python
initializes the main interpeter. The main interpreter contains a
dictionary of subinterpreters. Initially, this dictionary is
empty. With every request, as needed, subinterpreters are created, and
references to them are stored in this dictionary. The dictionary is
keyed on a string, also known as interpreter name. This name can be
any string. The main interpreter is named 'main_interpreter'
.
The way all other interpreters are named can be controlled by
PythonInterp*
directives. Default behavior is to name
interpreters using the Apache virtual server name (ServerName
directive). This means that all scripts in the same virtual server
execute in the same subinterpreter, but scripts in different virtual
servers execute in different subinterpreters with completely separate
namespaces. PythonInterpPerDirectory and PythonInterpPerDirective directives
alter the naming convention to use the absolute path of the directory
being accessed, or the directory in which the Python*Handler
was
encountered, respectively. PythonInterpreter can be used to force
the interpreter name to a specific string overriding any naming
conventions.
Once created, a subinterpreter will be reused for subsequent requests. It is never destroyed and exists until the Apache process ends.
You can find out the name of the interpreter under which you’re
running by peeking at request.interpreter
.
注釈
If any module is being used which has a C code component that uses
the simplified API for access to the Global Interpreter Lock (GIL)
for Python extension modules, then the interpreter name must be
forcibly set to be 'main_interpreter'
. This is necessary as such
a module will only work correctly if run within the context of the
first Python interpreter created by the process. If not forced to
run under the 'main_interpreter'
, a range of Python errors can
arise, each typically referring to code being run in restricted
mode.
参考
- http://www.python.org/doc/current/api/api.html
- Python C Language API
- http://www.python.org/peps/pep-0311.html
- PEP 0311 - Simplified Global Interpreter Lock Acquisition for Extensions
Overview of a Request Handler¶
A handler is a function that processes a particular phase of a request. Apache processes requests in phases - read the request, process headers, provide content, etc. For every phase, it will call handlers, provided by either the Apache core or one of its modules, such as mod_python which passes control to functions provided by the user and written in Python. A handler written in Python is not any different from a handler written in C, and follows these rules:
A handler function will always be passed a reference to a request
object. (Throughout this manual, the request object is often referred
to by the req
variable.)
Every handler can return:
apache.OK
, meaning this phase of the request was handled by this handler and no errors occurred.apache.DECLINED
, meaning this handler has not handled this phase of the request to completion and Apache needs to look for another handler in subsequent modules.apache.HTTP_ERROR
, meaning an HTTP error occurred. HTTP_ERROR can be any of the following:HTTP_CONTINUE = 100 HTTP_SWITCHING_PROTOCOLS = 101 HTTP_PROCESSING = 102 HTTP_OK = 200 HTTP_CREATED = 201 HTTP_ACCEPTED = 202 HTTP_NON_AUTHORITATIVE = 203 HTTP_NO_CONTENT = 204 HTTP_RESET_CONTENT = 205 HTTP_PARTIAL_CONTENT = 206 HTTP_MULTI_STATUS = 207 HTTP_MULTIPLE_CHOICES = 300 HTTP_MOVED_PERMANENTLY = 301 HTTP_MOVED_TEMPORARILY = 302 HTTP_SEE_OTHER = 303 HTTP_NOT_MODIFIED = 304 HTTP_USE_PROXY = 305 HTTP_TEMPORARY_REDIRECT = 307 HTTP_BAD_REQUEST = 400 HTTP_UNAUTHORIZED = 401 HTTP_PAYMENT_REQUIRED = 402 HTTP_FORBIDDEN = 403 HTTP_NOT_FOUND = 404 HTTP_METHOD_NOT_ALLOWED = 405 HTTP_NOT_ACCEPTABLE = 406 HTTP_PROXY_AUTHENTICATION_REQUIRED= 407 HTTP_REQUEST_TIME_OUT = 408 HTTP_CONFLICT = 409 HTTP_GONE = 410 HTTP_LENGTH_REQUIRED = 411 HTTP_PRECONDITION_FAILED = 412 HTTP_REQUEST_ENTITY_TOO_LARGE = 413 HTTP_REQUEST_URI_TOO_LARGE = 414 HTTP_UNSUPPORTED_MEDIA_TYPE = 415 HTTP_RANGE_NOT_SATISFIABLE = 416 HTTP_EXPECTATION_FAILED = 417 HTTP_UNPROCESSABLE_ENTITY = 422 HTTP_LOCKED = 423 HTTP_FAILED_DEPENDENCY = 424 HTTP_INTERNAL_SERVER_ERROR = 500 HTTP_NOT_IMPLEMENTED = 501 HTTP_BAD_GATEWAY = 502 HTTP_SERVICE_UNAVAILABLE = 503 HTTP_GATEWAY_TIME_OUT = 504 HTTP_VERSION_NOT_SUPPORTED = 505 HTTP_VARIANT_ALSO_VARIES = 506 HTTP_INSUFFICIENT_STORAGE = 507 HTTP_NOT_EXTENDED = 510
As an alternative to returning an HTTP error code, handlers can
signal an error by raising the apache.SERVER_RETURN
exception, and providing an HTTP error code as the exception value,
e.g.:
raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN
Handlers can send content to the client using the request.write()
method.
Client data, such as POST requests, can be read by using the
request.read()
function.
An example of a minimalistic handler might be:
from mod_python import apache
def requesthandler(req):
req.content_type = "text/plain"
req.write("Hello World!")
return apache.OK
Overview of a Filter Handler¶
A filter handler is a function that can alter the input or the output of the server. There are two kinds of filters - input and output that apply to input from the client and output to the client respectively.
At this time mod_python supports only request-level filters, meaning that only the body of HTTP request or response can be filtered. Apache provides support for connection-level filters, which will be supported in the future.
A filter handler receives a filter object as its argument. The
request object is available as well via filter.req
, but all
writing and reading should be done via the filter’s object read and
write methods.
Filters need to be closed when a read operation returns None (indicating End-Of-Stream).
The return value of a filter is ignored. Filters cannot decline
processing like handlers, but the same effect can be achieved
by using the filter.pass_on()
method.
Filters must first be registered using PythonInputFilter
or
PythonOutputFilter
, then added using the Apache
Add/SetInputFilter
or Add/SetOutputFilter
directives.
Here is an example of how to specify an output filter, it tells the server that all .py files should processed by CAPITALIZE filter:
PythonOutputFilter capitalize CAPITALIZE
AddOutputFilter CAPITALIZE .py
And here is what the code for the capitalize.py
might look
like:
from mod_python import apache
def outputfilter(filter):
s = filter.read()
while s:
filter.write(s.upper())
s = filter.read()
if s is None:
filter.close()
When writing filters, keep in mind that a filter will be called any time anything upstream requests an IO operation, and the filter has no control over the amount of data passed through it and no notion of where in the request processing it is called. For example, within a single request, a filter may be called once or five times, and there is no way for the filter to know beforehand that the request is over and which of calls is last or first for this request, thought encounter of an EOS (None returned from a read operation) is a fairly strong indication of an end of a request.
Also note that filters may end up being called recursively in
subrequests. To avoid the data being altered more than once, always
make sure you are not in a subrequest by examining the request.main
value.
For more information on filters, see http://httpd.apache.org/docs-2.4/developer/filters.html.
Overview of a Connection Handler¶
A connection handler handles the connection, starting almost immediately from the point the TCP connection to the server was made.
Unlike HTTP handlers, connection handlers receive a connection object as an argument.
Connection handlers can be used to implement protocols. Here is an example of a simple echo server:
Apache configuration:
PythonConnectionHandler echo
Contents of echo.py
file:
from mod_python import apache
def connectionhandler(conn):
while 1:
conn.write(conn.readline())
return apache.OK
apache
– Access to Apache Internals.¶
The Python interface to Apache internals is contained in a module
appropriately named apache
, located inside the
mod_python
package. This module provides some important
objects that map to Apache internal structures, as well as some useful
functions, all documented below. (The request object also provides an
interface to Apache internals, it is covered in its own section of
this manual.)
The apache
module can only be imported by a script running
under mod_python. This is because it depends on a built-in module
_apache
provided by mod_python.
It is best imported like this:
from mod_python import apache
mod_python.apache
module defines the following functions and
objects. For a more in-depth look at Apache internals, see the
Apache Developer Page
Functions¶
-
apache.
log_error
(message[, level[, server]])¶ An interface to the Apache
ap_log_error()
function. message is a string with the error message, level is one of the following flags constants:APLOG_EMERG APLOG_ALERT APLOG_CRIT APLOG_ERR APLOG_WARNING APLOG_NOTICE APLOG_INFO APLOG_DEBUG APLOG_NOERRNO // DEPRECATED
server is a reference to a
request.server()
object. If server is not specified, then the error will be logged to the default error log, otherwise it will be written to the error log for the appropriate virtual server. When server is not specified, the setting of LogLevel does not apply, the LogLevel is dictated by an httpd compile-time default, usuallywarn
.If you have a reference to a request object available, consider using
request.log_error()
instead, it will prepend request-specific information such as the source IP of the request to the log entry.
-
apache.
import_module
(module_name[, autoreload=1, log=0, path=None])¶ This function can be used to import modules taking advantage of mod_python’s internal mechanism which reloads modules automatically if they have changed since last import.
module_name is a string containing the module name (it can contain dots, e.g.
mypackage.mymodule
); autoreload indicates whether the module should be reloaded if it has changed since last import; when log is true, a message will be written to the logs when a module is reloaded; path allows restricting modules to specific paths.Example:
from mod_python import apache module = apache.import_module('module_name', log=1)
-
apache.
allow_methods
([*args])¶ A convenience function to set values in
request.allowed()
.request.allowed()
is a bitmask that is used to construct the'Allow:'
header. It should be set before returning aHTTP_NOT_IMPLEMENTED
error.Arguments can be one or more of the following:
M_GET M_PUT M_POST M_DELETE M_CONNECT M_OPTIONS M_TRACE M_PATCH M_PROPFIND M_PROPPATCH M_MKCOL M_COPY M_MOVE M_LOCK M_UNLOCK M_VERSION_CONTROL M_CHECKOUT M_UNCHECKOUT M_CHECKIN M_UPDATE M_LABEL M_REPORT M_MKWORKSPACE M_MKACTIVITY M_BASELINE_CONTROL M_MERGE M_INVALID
-
apache.
exists_config
(name)¶ This function returns True if the Apache server was launched with the definition with the given name. This means that you can test whether Apache was launched with the
-DFOOBAR
parameter by callingapache.exists_config_define('FOOBAR')
.
-
apache.
stat
(fname, wanted)¶ This function returns an instance of an
mp_finfo
object describing information related to the file with namefname
. Thewanted
argument describes the minimum attributes which should be filled out. The resultant object can be assigned to therequest.finfo
attribute.
-
apache.
register_cleanup
(callable[, data])¶ Registers a cleanup that will be performed at child shutdown time. Equivalent to
server.register_cleanup()
, except that a request object is not required. Warning: do not pass directly or indirectly a request object in the data parameter. Since the callable will be called at server shutdown time, the request object won’t exist anymore and any manipulation of it in the handler will give undefined behaviour.
-
apache.
config_tree
()¶ Returns the server-level configuration tree. This tree does not include directives from .htaccess files. This is a copy of the tree, modifying it has no effect on the actual configuration.
-
apache.
server_root
()¶ Returns the value of ServerRoot.
-
apache.
mpm_query
(code)¶ Allows querying of the MPM for various parameters such as numbers of processes and threads. The return value is one of three constants:
AP_MPMQ_NOT_SUPPORTED = 0 # This value specifies whether # an MPM is capable of # threading or forking. AP_MPMQ_STATIC = 1 # This value specifies whether # an MPM is using a static # of # threads or daemons. AP_MPMQ_DYNAMIC = 2 # This value specifies whether # an MPM is using a dynamic # of # threads or daemons.
The code argument must be one of the following:
AP_MPMQ_MAX_DAEMON_USED = 1 # Max # of daemons used so far AP_MPMQ_IS_THREADED = 2 # MPM can do threading AP_MPMQ_IS_FORKED = 3 # MPM can do forking AP_MPMQ_HARD_LIMIT_DAEMONS = 4 # The compiled max # daemons AP_MPMQ_HARD_LIMIT_THREADS = 5 # The compiled max # threads AP_MPMQ_MAX_THREADS = 6 # # of threads/child by config AP_MPMQ_MIN_SPARE_DAEMONS = 7 # Min # of spare daemons AP_MPMQ_MIN_SPARE_THREADS = 8 # Min # of spare threads AP_MPMQ_MAX_SPARE_DAEMONS = 9 # Max # of spare daemons AP_MPMQ_MAX_SPARE_THREADS = 10 # Max # of spare threads AP_MPMQ_MAX_REQUESTS_DAEMON= 11 # Max # of requests per daemon AP_MPMQ_MAX_DAEMONS = 12 # Max # of daemons by config
Example:
if apache.mpm_query(apache.AP_MPMQ_IS_THREADED): # do something else: # do something else
Attributes¶
-
apache.
interpreter
¶ String. The name of the subinterpreter under which we’re running. (Read-Only)
-
apache.
main_server
¶ A
server
object for the main server. (Read-Only)
-
apache.
MODULE_MAGIC_NUMBER_MAJOR
¶ Integer. An internal to Apache version number useful to determine whether certain features should be available. See
MODULE_MAGIC_NUMBER_MINOR
.Major API changes that could cause compatibility problems for older modules such as structure size changes. No binary compatibility is possible across a change in the major version.
(Read-Only)
-
apache.
MODULE_MAGIC_NUMBER_MINOR
¶ Integer. An internal to Apache version number useful to determine whether certain features should be available. See
MODULE_MAGIC_NUMBER_MAJOR
.Minor API changes that do not cause binary compatibility problems.
(Read-Only)
Table Object (mp_table)¶
-
class
apache.
table
([mapping-or-sequence])¶ Returns a new empty object of type
mp_table
. See Section Table Object (mp_table) for description of the table object. The mapping-or-sequence will be used to provide initial values for the table.The table object is a wrapper around the Apache APR table. The table object behaves very much like a dictionary (including the Python 2.2 features such as support of the
in
operator, etc.), with the following differences:- Both keys and values must be strings.
- Key lookups are case-insensitive.
- Duplicate keys are allowed (see
table.add()
below). When there is more than one value for a key, a subscript operation returns a list.
Much of the information that Apache uses is stored in tables. For example,
request.headers_in()
andrequest.headers_out()
.All the tables that mod_python provides inside the request object are actual mappings to the Apache structures, so changing the Python table also changes the underlying Apache table.
In addition to normal dictionary-like behavior, the table object also has the following method:
-
add
(key, val)¶ Allows for creating duplicate keys, which is useful when multiple headers, such as Set-Cookie: are required.
Request Object¶
The request object is a Python mapping to the Apache request_rec
structure. When a handler is invoked, it is always passed a single
argument - the request object. For brevity, we often refer to it here
and throughout the code as req
.
You can dynamically assign attributes to it as a way to communicate between handlers.
Request Methods¶
-
request.
add_cgi_vars
()¶ Calls Apache function
ap_add_common_vars()
followed some code very similar to Apacheap_add_cgi_vars()
with the exception of calculatingPATH_TRANSLATED
value, thereby avoiding sub-requests and filesystem access used in theap_add_cgi_vars()
implementation.
-
request.
add_common_vars
()¶ Use of this method is discouraged, use
request.add_cgi_vars()
instead.Calls the Apache
ap_add_common_vars()
function. After a call to this method,request.subprocess_env
will contain some CGI information.
-
request.
add_handler
(htype, handler[, dir])¶ Allows dynamic handler registration. htype is a string containing the name of any of the apache request (but not filter or connection) handler directives, e.g.
'PythonHandler'
. handler is a string containing the name of the module and the handler function. Optional dir is a string containing the name of the directory to be added to the pythonpath. If no directory is specified, then, if there is already a handler of the same type specified, its directory is inherited, otherwise the directory of the presently executing handler is used. If there is a'PythonPath'
directive in effect, thensys.path
will be set exactly according to it (no directories added, the dir argument is ignored).A handler added this way only persists throughout the life of the request. It is possible to register more handlers while inside the handler of the same type. One has to be careful as to not to create an infinite loop this way.
Dynamic handler registration is a useful technique that allows the code to dynamically decide what will happen next. A typical example might be a
PythonAuthenHandler
that will assign differentPythonHandlers
based on the authorization level, something like:if manager: req.add_handler("PythonHandler", "menu::admin") else: req.add_handler("PythonHandler", "menu::basic")
注釈
If you pass this function an invalid handler, an exception will be generated at the time an attempt is made to find the handler.
-
request.
add_input_filter
(filter_name)¶ Adds the named filter into the input filter chain for the current request. The filter should be added before the first attempt to read any data from the request.
-
request.
add_output_filter
(filter_name)¶ Adds the named filter into the output filter chain for the current request. The filter should be added before the first attempt to write any data for the response.
Provided that all data written is being buffered and not flushed, this could be used to add the “CONTENT_LENGTH” filter into the chain of output filters. The purpose of the “CONTENT_LENGTH” filter is to add a
Content-Length:
header to the response.:req.add_output_filter("CONTENT_LENGTH") req.write("content",0)
-
request.
allow_methods
(methods[, reset])¶ Adds methods to the
request.allowed_methods()
list. This list will be passed in Allowed: header ifHTTP_METHOD_NOT_ALLOWED
orHTTP_NOT_IMPLEMENTED
is returned to the client. Note that Apache doesn’t do anything to restrict the methods, this list is only used to construct the header. The actual method-restricting logic has to be provided in the handler code.methods is a sequence of strings. If reset is 1, then the list of methods is first cleared.
-
request.
auth_name
()¶ Returns AuthName setting.
-
request.
auth_type
()¶ Returns AuthType setting.
-
request.
construct_url
(uri)¶ This function returns a fully qualified URI string from the path specified by uri, using the information stored in the request to determine the scheme, server name and port. The port number is not included in the string if it is the same as the default port 80.
For example, imagine that the current request is directed to the virtual server www.modpython.org at port 80. Then supplying
'/index.html'
will yield the string'http://www.modpython.org/index.html'
.
-
request.
discard_request_body
()¶ Tests for and reads any message body in the request, simply discarding whatever it receives.
-
request.
document_root
()¶ Returns DocumentRoot setting.
-
request.
get_basic_auth_pw
()¶ Returns a string containing the password when Basic authentication is used.
On Python 3 the string will be decoded to Unicode using Latin1.
-
request.
get_config
()¶ Returns a reference to the table object containing the mod_python configuration in effect for this request except for
Python*Handler
andPythonOption
(The latter can be obtained viarequest.get_options()
. The table has directives as keys, and their values, if any, as values.
-
request.
get_remote_host
([type[, str_is_ip]])¶ This method is used to determine remote client’s DNS name or IP number. The first call to this function may entail a DNS look up, but subsequent calls will use the cached result from the first call.
The optional type argument can specify the following:
apache.REMOTE_HOST
Look up the DNS name. Return None if Apache directiveHostNameLookups
isOff
or the hostname cannot be determined.apache.REMOTE_NAME
(Default) Return the DNS name if possible, or the IP (as a string in dotted decimal notation) otherwise.apache.REMOTE_NOLOOKUP
Don’t perform a DNS lookup, return an IP. Note: if a lookup was performed prior to this call, then the cached host name is returned.apache.REMOTE_DOUBLE_REV
Force a double-reverse lookup. On failure, return None.
If str_is_ip is
None
or unspecified, then the return value is a string representing the DNS name or IP address.If the optional str_is_ip argument is not
None
, then the return value is an(address, str_is_ip)
tuple, wherestr_is_ip
is non-zero ifaddress
is an IP address string.On failure,
None
is returned.
-
request.
get_options
()¶ Returns a reference to the table object containing the options set by the
PythonOption
directives.
-
request.
internal_redirect
(new_uri)¶ Internally redirects the request to the new_uri. new_uri must be a string.
The httpd server handles internal redirection by creating a new request object and processing all request phases. Within an internal redirect,
request.prev()
will contain a reference to a request object from which it was redirected.
-
request.
is_https
()¶ Returns non-zero if the connection is using SSL/TLS. Will always return zero if the mod_ssl Apache module is not loaded.
You can use this method during any request phase, unlike looking for the
HTTPS
variable in therequest.subprocess_env
member dictionary. This makes it possible to write an authentication or access handler that makes decisions based upon whether SSL is being used.Note that this method will not determine the quality of the encryption being used. For that you should call the ssl_var_lookup method to get one of the SSL_CIPHER* variables.
-
request.
log_error
(message[, level])¶ An interface to the Apache ap_log_rerror function. message is a string with the error message, level is one of the following flags constants:
APLOG_EMERG APLOG_ALERT APLOG_CRIT APLOG_ERR APLOG_WARNING APLOG_NOTICE APLOG_INFO APLOG_DEBUG APLOG_NOERRNO
If you need to write to log and do not have a reference to a request object, use the
apache.log_error()
function.
-
request.
meets_conditions
()¶ Calls the Apache
ap_meets_conditions()
function which returns a status code. If status isapache.OK
, generate the content of the response normally. If not, simply return status. Note that mtime (and possibly the ETag header) should be set as appropriate prior to calling this function. The same goes forrequest.status()
if the status differs fromapache.OK
.Example:
# ... r.headers_out['ETag'] = '"1130794f-3774-4584-a4ea-0ab19e684268"' r.headers_out['Expires'] = 'Mon, 18 Apr 2005 17:30:00 GMT' r.update_mtime(1000000000) r.set_last_modified() status = r.meets_conditions() if status != apache.OK: return status # ... do expensive generation of the response content ...
-
request.
requires
()¶ Returns a tuple of strings of arguments to
require
directive.For example, with the following apache configuration:
AuthType Basic require user joe require valid-user
request.requires()
would return('user joe', 'valid-user')
.
-
request.
read
([len])¶ Reads at most len bytes directly from the client, returning a string with the data read. If the len argument is negative or omitted, reads all data given by the client.
This function is affected by the
Timeout
Apache configuration directive. The read will be aborted and anIOError
raised if theTimeout
is reached while reading client data.This function relies on the client providing the
Content-length
header. Absence of theContent-length
header will be treated as ifContent-length: 0
was supplied.Incorrect
Content-length
may cause the function to try to read more data than available, which will make the function block until aTimeout
is reached.On Python 3 the output is always bytes.
-
request.
readline
([len])¶ Like
request.read()
but reads until end of line.注釈
In accordance with the HTTP specification, most clients will be terminating lines with
'\r\n'
rather than simply'\n'
.
-
request.
readlines
([sizehint])¶ Reads all lines using
request.readline()
and returns a list of the lines read. If the optional sizehint parameter is given in, the method will read at least sizehint bytes of data, up to the completion of the line in which the sizehint bytes limit is reached.
-
request.
register_cleanup
(callable[, data])¶ Registers a cleanup. Argument callable can be any callable object, the optional argument data can be any object (default is
None
). At the very end of the request, just before the actual request record is destroyed by Apache, callable will be called with one argument, data.It is OK to pass the request object as data, but keep in mind that when the cleanup is executed, the request processing is already complete, so doing things like writing to the client is completely pointless.
If errors are encountered during cleanup processing, they should be in error log, but otherwise will not affect request processing in any way, which makes cleanup bugs sometimes hard to spot.
If the server is shut down before the cleanup had a chance to run, it’s possible that it will not be executed.
-
request.
register_input_filter
(filter_name, filter[, dir])¶ Allows dynamic registration of mod_python input filters. filter_name is a string which would then subsequently be used to identify the filter. filter is a string containing the name of the module and the filter function. Optional dir is a string containing the name of the directory to be added to the pythonpath. If there is a
PythonPath
directive in effect, thensys.path
will be set exactly according to it (no directories added, the dir argument is ignored).The registration of the filter this way only persists for the life of the request. To actually add the filter into the chain of input filters for the current request
request.add_input_filter()
would be used.
-
request.
register_output_filter
(filter_name, filter[, dir])¶ Allows dynamic registration of mod_python output filters. filter_name is a string which would then subsequently be used to identify the filter. filter is a string containing the name of the module and the filter function. Optional dir is a string containing the name of the directory to be added to the pythonpath. If there is a
PythonPath
directive in effect, thensys.path
will be set exactly according to it (no directories added, the dir argument is ignored).The registration of the filter this way only persists for the life of the request. To actually add the filter into the chain of output filters for the current request
request.add_output_filter()
would be used.
-
request.
sendfile
(path[, offset, len])¶ Sends len bytes of file path directly to the client, starting at offset offset using the server’s internal API. offset defaults to 0, and len defaults to -1 (send the entire file).
Returns the number of bytes sent, or raises an IOError exception on failure.
This function provides the most efficient way to send a file to the client.
-
request.
set_etag
()¶ Sets the outgoing
'ETag'
header.
-
request.
set_last_modified
()¶ Sets the outgoing
Last-Modified
header based on value ofmtime
attribute.
-
request.
ssl_var_lookup
(var_name)¶ Looks up the value of the named SSL variable. This method queries the mod_ssl Apache module directly, and may therefore be used in early request phases (unlike using the
request.subprocess_env
member.If the mod_ssl Apache module is not loaded or the variable is not found then
None
is returned.If you just want to know if a SSL or TLS connection is being used, you may consider calling the
is_https
method instead.It is unfortunately not possible to get a list of all available variables with the current mod_ssl implementation, so you must know the name of the variable you want. Some of the potentially useful ssl variables are listed below. For a complete list of variables and a description of their values see the mod_ssl documentation.:
SSL_CIPHER SSL_CLIENT_CERT SSL_CLIENT_VERIFY SSL_PROTOCOL SSL_SESSION_ID
注釈
Not all SSL variables are defined or have useful values in every request phase. Also use caution when relying on these values for security purposes, as SSL or TLS protocol parameters can often be renegotiated at any time during a request.
-
request.
update_mtime
(dependency_mtime)¶ If ependency_mtime is later than the value in the
mtime
attribute, sets the attribute to the new value.
-
request.
write
(string[, flush=1])¶ Writes string directly to the client, then flushes the buffer, unless flush is 0. Unicode strings are encoded using
utf-8
encoding.
-
request.
flush
()¶ Flushes the output buffer.
-
request.
set_content_length
(len)¶ Sets the value of
request.clength
and the'Content-Length'
header to len. Note that after the headers have been sent out (which happens just before the first byte of the body is written, i.e. first call torequest.write()
), calling the method is meaningless.
Request Members¶
-
request.
connection
¶ A
connection
object associated with this request. See Connection Object (mp_conn) Object for more details. (Read-Only)
-
request.
server
¶ A server object associated with this request. See Server Object (mp_server) for more details. (Read-Only)
-
request.
next
¶ If this is an internal redirect, the request object we redirect to. (Read-Only)
-
request.
prev
¶ If this is an internal redirect, the request object we redirect from. (Read-Only)
-
request.
main
¶ If this is a sub-request, pointer to the main request. (Read-Only)
-
request.
the_request
¶ String containing the first line of the request. (Read-Only)
-
request.
assbackwards
¶ Indicates an HTTP/0.9 “simple” request. This means that the response will contain no headers, only the body. Although this exists for backwards compatibility with obsolescent browsers, some people have figured out that setting assbackwards to 1 can be a useful technique when including part of the response from an internal redirect to avoid headers being sent.
-
request.
proxyreq
¶ A proxy request: one of
apache.PROXYREQ_*
values.
-
request.
header_only
¶ A boolean value indicating HEAD request, as opposed to GET. (Read-Only)
-
request.
protocol
¶ Protocol, as given by the client, or
'HTTP/0.9'
. Same as CGISERVER_PROTOCOL
. (Read-Only)
-
request.
proto_num
¶ Integer. Number version of protocol; 1.1 = 1001 (Read-Only)
-
request.
hostname
¶ String. Host, as set by full URI or Host: header. (Read-Only)
-
request.
request_time
¶ A long integer. When request started. (Read-Only)
-
request.
status_line
¶ Status line. E.g.
'200 OK'
. (Read-Only)
-
request.
status
¶ Status. One of
apache.HTTP_*
values.
-
request.
method
¶ A string containing the method -
'GET'
,'HEAD'
,'POST'
, etc. Same as CGIREQUEST_METHOD
. (Read-Only)
-
request.
method_number
¶ Integer containing the method number. (Read-Only)
-
request.
allowed
¶ Integer. A bitvector of the allowed methods. Used to construct the Allowed: header when responding with
HTTP_METHOD_NOT_ALLOWED
orHTTP_NOT_IMPLEMENTED
. This field is for Apache’s internal use, to set theAllowed:
methods userequest.allow_methods()
method, described in section Request Methods. (Read-Only)
-
request.
allowed_xmethods
¶ Tuple. Allowed extension methods. (Read-Only)
-
request.
allowed_methods
¶ Tuple. List of allowed methods. Used in relation with
METHOD_NOT_ALLOWED
. This member can be modified viarequest.allow_methods()
described in section Request Methods. (Read-Only)
-
request.
sent_bodyct
¶ Integer. Byte count in stream is for body. (?) (Read-Only)
-
request.
bytes_sent
¶ Long integer. Number of bytes sent. (Read-Only)
-
request.
mtime
¶ Long integer. Time the resource was last modified. (Read-Only)
-
request.
chunked
¶ Boolean value indicating when sending chunked transfer-coding. (Read-Only)
-
request.
range
¶ String. The
Range:
header. (Read-Only)
-
request.
clength
¶ Long integer. The “real” content length. (Read-Only)
-
request.
remaining
¶ Long integer. Bytes left to read. (Only makes sense inside a read operation.) (Read-Only)
-
request.
read_length
¶ Long integer. Number of bytes read. (Read-Only)
-
request.
read_body
¶ Integer. How the request body should be read. (Read-Only)
-
request.
read_chunked
¶ Boolean. Read chunked transfer coding. (Read-Only)
-
request.
expecting_100
¶ Boolean. Is client waiting for a 100 (
HTTP_CONTINUE
) response. (Read-Only)
-
request.
err_headers_out
¶ These headers get send with the error response, instead of headers_out.
-
request.
subprocess_env
¶ A
table
object containing environment information typically usable for CGI. You may have to callrequest.add_common_vars()
andrequest.add_cgi_vars()
first to fill in the information you need.
-
request.
notes
¶ A
table
object that could be used to store miscellaneous general purpose info that lives for as long as the request lives. If you need to pass data between handlers, it’s better to simply add members to the request object than to userequest.notes
.
-
request.
phase
¶ The phase currently being being processed, e.g.
'PythonHandler'
. (Read-Only)
-
request.
interpreter
¶ The name of the subinterpreter under which we’re running. (Read-Only)
-
request.
content_type
¶ String. The content type. Mod_python maintains an internal flag (
request._content_type_set
) to keep track of whetherrequest.content_type
was set manually from within Python. The publisher handler uses this flag in the following way: whenrequest.content_type
isn’t explicitly set, it attempts to guess the content type by examining the first few bytes of the output.
-
request.
content_languages
¶ Tuple. List of strings representing the content languages.
-
request.
handler
¶ The symbolic name of the content handler (as in module, not mod_python handler) that will service the request during the response phase. When the SetHandler/AddHandler directives are used to trigger mod_python, this will be set to
'mod_python'
by mod_mime. A mod_python handler executing prior to the response phase may also set this to'mod_python'
along with callingrequest.add_handler()
to register a mod_python handler for the response phase:def typehandler(req): if os.path.splitext(req.filename)[1] == ".py": req.handler = "mod_python" req.add_handler("PythonHandler", "mod_python.publisher") return apache.OK return apache.DECLINED
-
request.
content_encoding
¶ String. Content encoding. (Read-Only)
-
request.
vlist_validator
¶ Integer. Variant list validator (if negotiated). (Read-Only)
-
request.
user
¶ If an authentication check is made, this will hold the user name. Same as CGI
REMOTE_USER
.On Python 3 the string is decoded using Latin1. (Different browsers use different encodings for non-Latin1 characters for the basic authentication string making a solution that fits all impossible, you can always decode the header manually.)
注釈
request.get_basic_auth_pw()
must be called prior to using this value.
-
request.
ap_auth_type
¶ Authentication type. Same as CGI
AUTH_TYPE
.
-
request.
no_cache
¶ Boolean. This response cannot be cached.
-
request.
no_local_copy
¶ Boolean. No local copy exists.
-
request.
unparsed_uri
¶ The URI without any parsing performed. (Read-Only)
-
request.
uri
¶ The path portion of the URI.
-
request.
filename
¶ String. File name being requested.
-
request.
canonical_filename
¶ String. The true filename (
request.filename
is canonicalized if they don’t match).
-
request.
path_info
¶ String. What follows after the file name, but is before query args, if anything. Same as CGI
PATH_INFO
.
-
request.
args
¶ String. Same as CGI
QUERY_ARGS
.
-
request.
finfo
¶ A file information object with type
mp_finfo
, analogous to the result of the POSIX stat function, describing the file pointed to by the URI. The object provides the attributesfname
,filetype
,valid
,protection
,user
,group
,size
,inode
,device
,nlink
,atime
,mtime
,ctime
andname
.The attribute may be assigned to using the result of
apache.stat()
. For example:if req.finfo.filetype == apache.APR_DIR: req.filename = posixpath.join(req.filename, 'index.html') req.finfo = apache.stat(req.filename, apache.APR_FINFO_MIN)
For backward compatibility, the object can also be accessed as if it were a tuple. The
apache
module defines a set ofFINFO_*
constants that should be used to access elements of this tuple.:user = req.finfo[apache.FINFO_USER]
-
request.
parsed_uri
¶ Tuple. The URI broken down into pieces.
(scheme, hostinfo, user, password, hostname, port, path, query, fragment)
. Theapache
module defines a set ofURI_*
constants that should be used to access elements of this tuple. Example:fname = req.parsed_uri[apache.URI_PATH]
(Read-Only)
-
request.
used_path_info
¶ Flag to accept or reject path_info on current request.
-
request.
eos_sent
¶ Boolean. EOS bucket sent. (Read-Only)
-
request.
useragent_addr
¶ Apache 2.4 only
The (address, port) tuple for the user agent.
This attribute should reflect the address of the user agent and not necessarily the other end of the TCP connection, for which there is
connection.client_addr
. (Read-Only)
-
request.
useragent_ip
¶ Apache 2.4 only
String with the IP of the user agent. Same as CGI
REMOTE_ADDR
.This attribute should reflect the address of the user agent and not necessarily the other end of the TCP connection, for which there is
connection.client_ip
. (Read-Only)
Connection Object (mp_conn)¶
The connection object is a Python mapping to the Apache
conn_rec
structure.
Connection Methods¶
-
connection.
log_error
(message[, level])¶ An interface to the Apache
ap_log_cerror
function. message is a string with the error message, level is one of the following flags constants:APLOG_EMERG APLOG_ALERT APLOG_CRIT APLOG_ERR APLOG_WARNING APLOG_NOTICE APLOG_INFO APLOG_DEBUG APLOG_NOERRNO If you need to write to log and do not have a reference to a connection or request object, use the :func:`apache.log_error` function.
-
connection.
read
([length])¶ Reads at most length bytes from the client. The read blocks indefinitely until there is at least one byte to read. If length is -1, keep reading until the socket is closed from the other end (This is known as
EXHAUSTIVE
mode in the http server code).This method should only be used inside Connection Handlers.
注釈
The behavior of this method has changed since version 3.0.3. In 3.0.3 and prior, this method would block until length bytes was read.
-
connection.
readline
([length])¶ Reads a line from the connection or up to length bytes.
This method should only be used inside Connection Handlers.
-
connection.
write
(string)¶ Writes string to the client.
This method should only be used inside Connection Handlers.
Connection Members¶
-
connection.
base_server
¶ A
server
object for the physical vhost that this connection came in through. (Read-Only)
-
connection.
local_addr
¶ The (address, port) tuple for the server. (Read-Only)
-
connection.
remote_addr
¶ Deprecated in Apache 2.4, use client_addr. (Aliased to client_addr for backward compatibility)
The (address, port) tuple for the client. (Read-Only)
-
connection.
client_addr
¶ Apache 2.4 only
The (address, port) tuple for the client.
This attribute reflects the other end of the TCP connection, which may not always be the address of the user agent. A more accurate source of the user agent address is
request.useragent_addr
. (Read-Only)
-
connection.
remote_ip
¶ Deprecated in Apache 2.4, use client_ip. (Aliased to client_ip for backward compatibility)
String with the IP of the client. In Apache 2.2 same as CGI
REMOTE_ADDR
. (Read-Only)
-
connection.
client_ip
¶ Apache 2.4 only
String with the IP of the client.
This attribute reflects the other end of the TCP connection, which may not always be the address of the user agent. A more accurate source of the user agent address is
request.useragent_ip
.(Read-Only)
-
connection.
remote_host
¶ String. The DNS name of the remote client. None if DNS has not been checked,
''
(empty string) if no name found. Same as CGIREMOTE_HOST
. (Read-Only)
-
connection.
remote_logname
¶ Remote name if using RFC 1413 (ident). Same as CGI
REMOTE_IDENT
. (Read-Only)
-
connection.
aborted
¶ Boolean. True is the connection is aborted. (Read-Only)
-
connection.
keepalive
¶ Integer. 1 means the connection will be kept for the next request, 0 means “undecided”, -1 means “fatal error”. (Read-Only)
-
connection.
double_reverse
¶ Integer. 1 means double reverse DNS lookup has been performed, 0 means not yet, -1 means yes and it failed. (Read-Only)
-
connection.
keepalives
¶ The number of times this connection has been used. (?) (Read-Only)
-
connection.
local_ip
¶ String with the IP of the server. (Read-Only)
-
connection.
local_host
¶ DNS name of the server. (Read-Only)
-
connection.
id
¶ Long. A unique connection id. (Read-Only)
Filter Object (mp_filter)¶
A filter object is passed to mod_python input and output filters. It is used to obtain filter information, as well as get and pass information to adjacent filters in the filter stack.
Filter Methods¶
-
filter.
pass_on
()¶ Passes all data through the filter without any processing.
-
filter.
read
([length])¶ Reads at most len bytes from the next filter, returning a string with the data read or None if End Of Stream (EOS) has been reached. A filter must be closed once the EOS has been encountered.
If the length argument is negative or omitted, reads all data currently available.
-
filter.
readline
([length])¶ Reads a line from the next filter or up to length bytes.
-
filter.
write
(string)¶ Writes string to the next filter.
-
filte.
flush
()¶ Flushes the output by sending a FLUSH bucket.
-
filter.
close
()¶ Closes the filter and sends an EOS bucket. Any further IO operations on this filter will throw an exception.
-
filter.
disable
()¶ Tells mod_python to ignore the provided handler and just pass the data on. Used internally by mod_python to print traceback from exceptions encountered in filter handlers to avoid an infinite loop.
Filter Members¶
-
filter.
closed
¶ A boolean value indicating whether a filter is closed. (Read-Only)
-
filter.
name
¶ String. The name under which this filter is registered. (Read-Only)
-
filter.
req
¶ A reference to the request object. (Read-Only)
-
filter.
is_input
¶ Boolean. True if this is an input filter. (Read-Only)
-
filter.
handler
¶ String. The name of the Python handler for this filter as specified in the configuration. (Read-Only)
Server Object (mp_server)¶
The request object is a Python mapping to the Apache
request_rec
structure. The server structure describes the
server (possibly virtual server) serving the request.
Server Methods¶
-
server.
get_config
()¶ Similar to
request.get_config()
, but returns a table object holding only the mod_python configuration defined at global scope within the Apache configuration. That is, outside of the context of any VirtualHost, Location, Directory or Files directives.
-
server.
get_options
()¶ Similar to
request.get_options()
, but returns a table object holding only the mod_python options defined at global scope within the Apache configuration. That is, outside of the context of any VirtualHost, Location, Directory or Files directives.
-
server.
log_error
(message[level])¶ An interface to the Apache
ap_log_error
function. message is a string with the error message, level is one of the following flags constants:APLOG_EMERG APLOG_ALERT APLOG_CRIT APLOG_ERR APLOG_WARNING APLOG_NOTICE APLOG_INFO APLOG_DEBUG APLOG_NOERRNO
If you need to write to log and do not have a reference to a server or request object, use the
apache.log_error()
function.
-
server.
register_cleanup
(request, callable[, data])¶ Registers a cleanup. Very similar to
req.register_cleanup()
, except this cleanup will be executed at child termination time. This function requires the request object be supplied to infer the interpreter name. If you don’t have any request object at hand, then you must use theapache.register_cleanup()
variant.注釈
Warning: do not pass directly or indirectly a request object in the data parameter. Since the callable will be called at server shutdown time, the request object won’t exist anymore and any manipulation of it in the callable will give undefined behaviour.
Server Members¶
-
server.
defn_name
¶ String. The name of the configuration file where the server definition was found. (Read-Only)
-
server.
defn_line_number
¶ Integer. Line number in the config file where the server definition is found. (Read-Only)
-
server.
server_admin
¶ Value of the
ServerAdmin
directive. (Read-Only)
-
server.
server_hostname
¶ Value of the
ServerName
directive. Same as CGISERVER_NAME
. (Read-Only)
-
server.
names
¶ Tuple. List of normal server names specified in the
ServerAlias
directive. This list does not include wildcarded names, which are listed separately inwild_names
. (Read-Only)
-
server.
wild_names
¶ Tuple. List of wildcarded server names specified in the
ServerAlias
directive. (Read-Only)
-
server.
port
¶ Integer. TCP/IP port number. Same as CGI
SERVER_PORT
. This member appears to be 0 on Apache 2.0, look at req.connection.local_addr instead (Read-Only)
-
server.
error_fname
¶ The name of the error log file for this server, if any. (Read-Only)
-
server.
loglevel
¶ Integer. Logging level. (Read-Only)
-
server.
is_virtual
¶ Boolean. True if this is a virtual server. (Read-Only)
-
server.
timeout
¶ Integer. Value of the
Timeout
directive. (Read-Only)
-
server.
keep_alive_timeout
¶ Integer. Keepalive timeout. (Read-Only)
-
server.
keep_alive_max
¶ Maximum number of requests per keepalive. (Read-Only)
-
server.
keep_alive
¶ Use persistent connections? (Read-Only)
-
server.
path
¶ String. Path for
ServerPath
(Read-Only)
-
server.
pathlen
¶ Integer. Path length. (Read-Only)
-
server.
limit_req_line
¶ Integer. Limit on size of the HTTP request line. (Read-Only)
-
server.
limit_req_fieldsize
¶ Integer. Limit on size of any request header field. (Read-Only)
-
server.
limit_req_fields
¶ Integer. Limit on number of request header fields. (Read-Only)
util
– Miscellaneous Utilities¶
The util
module provides a number of utilities handy to a web
application developer similar to those in the standard library
cgi
module. The implementations in the util
module are
much more efficient because they call directly into Apache API’s as
opposed to using CGI which relies on the environment to pass
information.
The recommended way of using this module is:
from mod_python import util
参考
- RFC 3875
- for detailed information on the CGI specification
FieldStorage class¶
Access to form data is provided via the FieldStorage
class. This class is similar to the standard library module
cgi.FieldStorage
-
class
util.
FieldStorage
(req[, keep_blank_values[, strict_parsing[, file_callback[, field_callback]]]])¶ This class provides uniform access to HTML form data submitted by the client. req is an instance of the mod_python
request
object.The optional argument keep_blank_values is a flag indicating whether blank values in URL encoded form data should be treated as blank strings. The default is false, which means that blank values are ignored as if they were not included.
The optional argument strict_parsing is not yet implemented.
The optional argument file_callback allows the application to override both file creation/deletion semantics and location. See FieldStorage Examples for additional information. New in version 3.2
The optional argument field_callback allows the application to override both the creation/deletion semantics and behavior. New in version 3.2
During initialization,
FieldStorage
class reads all of the data provided by the client. Since all data provided by the client is consumed at this point, there should be no more than oneFieldStorage
class instantiated per single request, nor should you make any attempts to read client data before or after instantiating aFieldStorage
. A suggested strategy for dealing with this is that any handler should first check for the existence of aform
attribute within the request object. If this exists, it should be taken to be an existing instance of theFieldStorage
class and that should be used. If the attribute does not exist and needs to be created, it should be cached as theform
attribute of the request object so later handler code can use it.When the
FieldStorage
class instance is created, the data read from the client is then parsed into separate fields and packaged inField
objects, one per field. For HTML form inputs of typefile
, a temporary file is created that can later be accessed via theField.file
attribute of aField
object.The
FieldStorage
class has a mapping object interface, i.e. it can be treated like a dictionary in most instances, but is not strictly compatible as is it missing some methods provided by dictionaries and some methods don’t behave entirely like their counterparts, especially when there is more than one value associated with a form field. When used as a mapping, the keys are form input names, and the returned dictionary value can be:- An instance of
StringField
, containing the form input value. This is only when there is a single value corresponding to the input name.StringField
is a subclass ofstr
which provides the additionalStringField.value
attribute for compatibility with standard librarycgi
module. - An instance of a
Field
class, if the input is a file upload. - A list of
StringField
and/orField
objects. This is when multiple values exist, such as for a<select>
HTML form element.
注釈
Unlike the standard library
cgi
moduleFieldStorage
class, aField
object is returned only when it is a file upload. In all other cases the return is an instance ofStringField
. This means that you do not need to use theStringFile.value
attribute to access values of fields in most cases.In addition to standard mapping object methods,
FieldStorage
objects have the following attributes:- An instance of
FieldStorage
methods¶
util.
add_field
(name, value)¶Adds an additional form field with name and value. If a form field already exists with name, the value will be added to the list of existing values for the form field. This method should be used for adding additional fields in preference to adding new fields direct to the list of fields.
If the value associated with a field should be replaced when it already exists, rather than an additional value being associated with the field, the dictionary like subscript operator should be used to set the value, or the existing field deleted altogether first using the
del
operator.
util.
clear
()¶Removes all form fields. Individual form fields can be deleted using the
del
operator.
util.
get
(name, default)¶If there is only one value associated with form field name, that single value will be returned. If there are multiple values, a list is returned holding all values. If no such form field or value exists then the method returns the value specified by the parameter default. A subscript operator is also available which yields the same result except that an exception will be raised where the form field name does not exist.
util.
getfirst
(name[, default])¶Always returns only one value associated with form field name. If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to
None
if not specified.
util.
getlist
(name)¶This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.
util.
has_key
(name)¶Returns
True
if name is a valid form field. Thein
operator is also supported and will call this method.
util.
items
()¶Returns a list consisting of tuples for each combination of form field name and value.
util.
keys
()¶This method returns the names of the form fields. The
len
operator is also supported and will return the number of names which would be returned by this method.
FieldStorage Examples¶
The following examples demonstrate how to use the file_callback parameter of the
FieldStorage
constructor to control file object creation. TheStorage
classes created in both examples derive from FileType, thereby providing extended file functionality.These examples are provided for demonstration purposes only. The issue of temporary file location and security must be considered when providing such overrides with mod_python in production use.
Simple file control using class constructor¶
This example uses the
FieldStorage
class constructor to create the file object, allowing simple control. It is not advisable to add class variables to this if serving multiple sites from apache. In that case use the factory method instead:class Storage(file): def __init__(self, advisory_filename): self.advisory_filename = advisory_filename self.delete_on_close = True self.already_deleted = False self.real_filename = '/someTempDir/thingy-unique-thingy' super(Storage, self).__init__(self.real_filename, 'w+b') def close(self): if self.already_deleted: return super(Storage, self).close() if self.delete_on_close: self.already_deleted = True os.remove(self.real_filename) request_data = util.FieldStorage(request, keep_blank_values=True, file_callback=Storage)
Advanced file control using object factory¶
Using a object factory can provide greater control over the constructor parameters:
import os class Storage(file): def __init__(self, directory, advisory_filename): self.advisory_filename = advisory_filename self.delete_on_close = True self.already_deleted = False self.real_filename = directory + '/thingy-unique-thingy' super(Storage, self).__init__(self.real_filename, 'w+b') def close(self): if self.already_deleted: return super(Storage, self).close() if self.delete_on_close: self.already_deleted = True os.remove(self.real_filename) class StorageFactory: def __init__(self, directory): self.dir = directory def create(self, advisory_filename): return Storage(self.dir, advisory_filename) file_factory = StorageFactory(someDirectory) # [...sometime later...] request_data = util.FieldStorage(request, keep_blank_values=True, file_callback=file_factory.create)
Field class¶
-
class
util.
Field
¶ This class is used internally by
FieldStorage
and is not meant to be instantiated by the user. Each instance of aField
class represents an HTML Form input.Field
instances have the following attributes:-
name
¶ The input name.
-
value
¶ The input value. This attribute can be used to read data from a file upload as well, but one has to exercise caution when dealing with large files since when accessed via
value
, the whole file is read into memory.
-
file
¶ This is a file-like object. For file uploads it points to a
TemporaryFile
instance. (For more information see the TemporaryFile class in the standard python tempfile module.For simple values, it is a
StringIO
object, so you can read simple string values via this attribute instead of using thevalue
attribute as well.
-
filename
¶ The name of the file as provided by the client.
-
type
¶ The content-type for this input as provided by the client.
-
type_options
¶ This is what follows the actual content type in the
content-type
header provided by the client, if anything. This is a dictionary.
-
disposition
¶ The value of the first part of the
content-disposition
header.
-
disposition_options
¶ The second part (if any) of the
content-disposition
header in the form of a dictionary.
参考
- RFC 1867
- Form-based File Upload in HTML for a description of form-based file uploads
-
Other functions¶
-
util.
parse_qs
(qs[, keep_blank_values[, strict_parsing]])¶ This function is functionally equivalent to the standard library
cgi.parse_qs()
, except that it is written in C and is much faster.Parse a query string given as a string argument (data of type
application/x-www-form-urlencoded
). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.The optional argument keep_blank_values is a flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.
注釈
The strict_parsing argument is not yet implemented.
-
util.
parse_qsl
(qs[, keep_blank_values[, strict_parsing]])¶ This function is functionally equivalent to the standard library
cgi.parse_qsl()
, except that it is written in C and is much faster.Parse a query string given as a string argument (data of type
application/x-www-form-urlencoded
). Data are returned as a list of name, value pairs.The optional argument keep_blank_values is a flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.
注釈
The strict_parsing argument is not yet implemented.
-
util.
redirect
(req, location[, permanent=0[, text=None]])¶ This is a convenience function to redirect the browser to another location. When permanent is true,
MOVED_PERMANENTLY
status is sent to the client, otherwise it isMOVED_TEMPORARILY
. A short text is sent to the browser informing that the document has moved (for those rare browsers that do not support redirection); this text can be overridden by supplying a text string.If this function is called after the headers have already been sent, an
IOError
is raised.This function raises
apache.SERVER_RETURN
exception with a value ofapache.DONE
to ensuring that any later phases or stacked handlers do not run. If you do not want this, you can wrap the call toredirect()
in a try/except block catching theapache.SERVER_RETURN
.
Cookie
– HTTP State Management¶
The Cookie
module provides convenient ways for creating,
parsing, sending and receiving HTTP Cookies, as defined in the
specification published by Netscape.
注釈
Even though there are official IETF RFC’s describing HTTP State Management Mechanism using cookies, the de facto standard supported by most browsers is the original Netscape specification. Furthermore, true compliance with IETF standards is actually incompatible with many popular browsers, even those that claim to be RFC-compliant. Therefore, this module supports the current common practice, and is not fully RFC compliant.
More specifically, the biggest difference between Netscape and RFC
cookies is that RFC cookies are sent from the browser to the server
along with their attributes (like Path or Domain). The
Cookie
module ignore those incoming attributes, so all
incoming cookies end up as Netscape-style cookies, without any of
their attributes defined.
参考
- Persistent Client State - HTTP Cookies
- for the original Netscape specification.
- RFC 2109
- HTTP State Management Mechanism for the first RFC on Cookies.
- RFC 2694
- Use of HTTP State Management for guidelines on using Cookies.
- RFC 2965
- HTTP State Management Mechanism for the latest IETF standard.
- HTTP Cookies: Standards, Privacy, and Politics
- by David M. Kristol for an excellent overview of the issues surrounding standardization of Cookies.
Classes¶
-
class
Cookie.
Cookie
(name, value[, attributes])¶ This class is used to construct a single cookie named name and having value as the value. Additionally, any of the attributes defined in the Netscape specification and RFC2109 can by supplied as keyword arguments.
The attributes of the class represent cookie attributes, and their string representations become part of the string representation of the cookie. The
Cookie
class restricts attribute names to only valid values, specifically, only the following attributes are allowed:name, value, version, path, domain, secure, comment, expires, max_age, commentURL, discard, port, httponly, __data__
.The
__data__
attribute is a general-purpose dictionary that can be used for storing arbitrary values, when necessary (This is useful when subclassingCookie
).The
expires
attribute is a property whose value is checked upon setting to be in format'Wdy, DD-Mon-YYYY HH:MM:SS GMT'
(as dictated per Netscape cookie specification), or a numeric value representing time in seconds since beginning of epoch (which will be automatically correctly converted to GMT time string). An invalidexpires
value will raiseValueError
.When converted to a string, a
Cookie
will be in correct format usable as value in a'Cookie'
or'Set-Cookie'
header.注釈
Unlike the Python Standard Library Cookie classes, this class represents a single cookie (referred to as Morsel in Python Standard Library).
-
parse
(string)¶ This is a class method that can be used to create a
Cookie
instance from a cookie string string as passed in a header value. During parsing, attribute names are converted to lower case.Because this is a class method, it must be called explicitly specifying the class.
This method returns a dictionary of
Cookie
instances, not a singleCookie
instance.Here is an example of getting a single
Cookie
instance:mycookies = Cookie.parse("spam=eggs; expires=Sat, 14-Jun-2003 02:42:36 GMT") spamcookie = mycookies["spam"]
注釈
Because this method uses a dictionary, it is not possible to have duplicate cookies. If you would like to have more than one value in a single cookie, consider using a
MarshalCookie
.
-
-
class
Cookie.
SignedCookie
(name, value, secret[, attributes])¶ This is a subclass of
Cookie
. This class creates cookies whose name and value are automatically signed using HMAC (md5) with a provided secret secret, which must be a non-empty string.-
parse
(string, secret)¶ This method acts the same way as
Cookie.parse()
, but also verifies that the cookie is correctly signed. If the signature cannot be verified, the object returned will be of classCookie
:.. note::
Always check the types of objects returned by :meth:SignedCookie.parse(). If it is an instance of
Cookie
(as opposed toSignedCookie
), the signature verification has failed:# assume spam is supposed to be a signed cookie if type(spam) is not Cookie.SignedCookie: # do something that indicates cookie isn't signed correctly
-
-
class
Cookie.
MarshalCookie
(name, value, secret[, attributes])¶ This is a subclass of
SignedCookie
. It allows for value to be any marshallable objects. Core Python types such as string, integer, list, etc. are all marshallable object. For a complete list see marchal module documentation.When parsing, the signature is checked first, so incorrectly signed cookies will not be unmarshalled.
Functions¶
This is a convenience function for setting a cookie in request headers. req is a mod_python
Request
object. If cookie is an instance ofCookie
(or subclass thereof), then the cookie is set, otherwise, cookie must be a string, in which case aCookie
is constructed using cookie as name, value as the value, along with any validCookie
attributes specified as keyword arguments.This function will also set
'Cache-Control: no-cache="set-cookie"'
header to inform caches that the cookie value should not be cached.Here is one way to use this function:
c = Cookie.Cookie('spam', 'eggs', expires=time.time()+300) Cookie.add_cookie(req, c)
Here is another:
Cookie.add_cookie(req, ‘spam’, ‘eggs’, expires=time.time()+300)
This is a convenience function for retrieving cookies from incoming headers. req is a mod_python
Request
object. Class is a class whoseparse()
method will be used to parse the cookies, it defaults toCookie
. data can be any number of keyword arguments which, will be passed toparse()
(This is useful forsignedCookie
andMarshalCookie
which requiresecret
as an additional argument toparse()
). The set of cookies found is returned as a dictionary.
This is a convenience function for retrieving a single named cookie from incoming headers. req is a mod_python
Request
object. name is the name of the cookie. Class is a class whoseparse()
method will be used to parse the cookies, it defaults toCookie
. Data can be any number of keyword arguments which, will be passed toparse()
(This is useful forsignedCookie
andMarshalCookie
which requiresecret
as an additional argument toparse()
). The cookie if found is returned, otherwiseNone
is returned.
Examples¶
This example sets a simple cookie which expires in 300 seconds:
from mod_python import Cookie, apache
import time
def handler(req):
cookie = Cookie.Cookie('eggs', 'spam')
cookie.expires = time.time() + 300
Cookie.add_cookie(req, cookie)
req.write('This response contains a cookie!\n')
return apache.OK
This example checks for incoming marshal cookie and displays it to the
client. If no incoming cookie is present a new marshal cookie is set.
This example uses 'secret007'
as the secret for HMAC signature:
from mod_python import apache, Cookie
def handler(req):
cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
secret='secret007')
if cookies.has_key('spam'):
spamcookie = cookies['spam']
req.write('Great, a spam cookie was found: %s\n' \
% str(spamcookie))
if type(spamcookie) is Cookie.MarshalCookie:
req.write('Here is what it looks like decoded: %s=%s\n'
% (spamcookie.name, spamcookie.value))
else:
req.write('WARNING: The cookie found is not a \
MarshalCookie, it may have been tapered with!')
else:
# MarshaCookie allows value to be any marshallable object
value = {'egg_count': 32, 'color': 'white'}
Cookie.add_cookie(req, Cookie.MarshalCookie('spam', value, \
'secret007'))
req.write('Spam cookie not found, but we just set one!\n')
return apache.OK
Session
– Session Management¶
The Session
module provides objects for maintaining persistent
sessions across requests.
The module contains a BaseSession
class, which is not meant
to be used directly (it provides no means of storing a session),
DbmSession
class, which uses a dbm to store sessions, and
FileSession
class, which uses individual files to store
sessions.
The BaseSession
class also provides session locking, both
across processes and threads. For locking it uses APR global_mutexes
(a number of them is pre-created at startup) The mutex number is
computed by using modulus of the session id hash()
. (Therefore
it’s possible that different session id’s will have the same hash, but
the only implication is that those two sessions cannot be locked at
the same time resulting in a slight delay.)
Classes¶
-
Session.
Session
(req[, sid[, secret[, timeout[, lock]]]])¶ Session()
takes the same arguments asBaseSession
.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 ofDbmSession
,MemorySession
orFileSession
. Specifying custom session classes usingPythonOption
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
orMemorySession
.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 casesDbmSession
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, asMemorySession
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 compatibility with older versions of mod_python, you should use the now obsoletesession
option instead.
-
class
Session.
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 ofdict
. Data can be stored and retrieved from the session by using it as a dictionary.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 thePythonHandler
directive currently in effect was specified. E.g. if document root is/a/b/c
and the directoryPythonHandler
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 theLocation
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 themod_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 useSignedCookie
when generating cookies thereby making the session id almost impossible to fake. The default is to use plainCookie
(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 occurring 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 :meth:req.register_cleanup` to register a cleanup which will be executed after the request has been processed.
-
-
class
Session.
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 bytempfile.gettempdir()
standard library function. An alternative directory can be specified usingPythonOption mod_python.dbm_session.database_directory /path/to/directory
. The path and filename can can be overridden by settingPythonOption 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 compatibility with older versions of mod_python, you should continue to use the now obsoletesession_directory
andsession_dbm
options.The implementation uses Python
anydbm
module, which will default todbhash
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
Session.
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 usingPythonOption 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 compatibility with older versions of mod_python, you should continue to use the now obsoletesession_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
andPythonOption 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
Session.
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.
Examples¶
The following example demonstrates a simple hit counter.:
from mod_python import Session
def handler(req):
session = Session.Session(req)
try:
session['hits'] += 1
except:
session['hits'] = 1
session.save()
req.content_type = 'text/plain'
req.write('Hits: %d\n' % session['hits'])
return apache.OK
psp
– Python Server Pager¶
psp
モジュールは、特別なブラケット表記の中に Python コードを埋め込んだテキストドキュメント (HTMLも含みますが、それだけではありません) を、 mod_python ハンドラ内での実行に適した pure Python コードに変換します。
これにより、ASP や JSP などに似たスタイルで、動的なコンテンツを配信できる使い勝手のよいメカニズムを実現しています。
psp
の使っているパーザは (flex で生成した) C で書かれているため、非常に高速に動作します。
PSP の詳細は「 PSP ハンドラ の節を参照してください。}
ドキュメント中の Python の コード は、 '<%'
と '%>'
で囲わねばなりません。
Python の 式 は、 '<%='
と '%>'
で囲みます。
ディレクティブ は '<%@'
と '%>'
で囲みます。
コメント(処理後のコード中には入りません) は '<%--'
と '--%>'
で囲います。
コードと式の両方を HTML ドキュメントに埋め込んでいる簡単な PSP ページの例を以下に示します:
<html>
<%
import time
%>
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
</html>
内部では、PSP パーザが上のページを以下の Python コードに翻訳します::
req.write("""<html>
""")
import time
req.write("""
Hello world, the time is: """); req.write(str(time.strftime("%Y-%m-%d, %H:%M:%S"))); req.write("""
</html>
""")
このコードをハンドラ内で実行すると、 'Hello world, the time is: '
の後ろに現在の時刻が入ったページになります。
Python コードを使って、条件やループでページの一部分を表示できます。 Python コード内のブロックはインデントで表現されます。ある Python コード ブロックの最後の行のインデントは (コメント文であっても) ドキュメントの 末尾か、次の Python コードブロックまで持続します。
例を示します:
<html>
<%
for n in range(3):
# このインデントレベルが維持される
%>
<p>この行の出力は
三回繰り返す</p>
<%
# この行でブロックが終わる
%>
この行は一度しか表示されない<br>
</html>
上の例は、内部的には以下の Python コードに翻訳されます:
req.write("""<html>
""")
for n in range(3):
# このインデントレベルが維持される
req.write("""
<p>この行の出力は
三回繰り返す</p>
""")
# この行でブロックが終わる
req.write("""
この行は一度しか表示されない<br>
</html>
""")
パーザは賢くて、Python コードブロックの最後の行が ':'
で終っている場合にも、正しくインデントを推測します。
このことと、 '<% %>'
の中で改行に到達するとインデントがリセットされることを考慮すると、上のページは以下のようにも書けます:
<html>
<%
for n in range(3):
%>
<p>この行の出力は
三回繰り返す</p>
<%
%>
この行は一度しか表示されない<br>
</html>
とはいえ、このコードには困惑させられるでしょう。ですから、お作法として、ブロック間で説明用のコメントを入れておくよう強く勧めます。
現時点でサポートしているディレクティブは include
だけで、以下のようにして使います:
<%@ include file="/file/to/include"%>
parse()
を dir 引数つきで呼び出す場合には、file は相対パスで指定できます。それ以外の場合には絶対パスでなければなりません。
-
class
psp.
PSP
(req[, filename[, string[, vars]]])¶ PSP オブジェクトを表すクラスです。
req はリクエストオブジェクトです。 filename と string はオプションのキーワード引数で、 PSP コードのソースを表します。 これらの変数はいずれか一つだけを指定できます。両方とも指定しなかった場合、 filename に req.filename を使います。
vars はグローバル変数の辞書です。
run()
メソッドに変数を渡すと、ここで渡した vars の内容をオーバライドします。このクラスは PSP ハンドラが内部で利用しますが、汎用のテンプレートツールとしても使えます。
ファイルをソースに使う場合、指定したファイルから得たコードオブジェクトは、ファイル名と更新時刻をキーにしてメモリキャッシュ上に保存されます。 キャッシュは Python インタプリタ上ではグローバルな値です。 従って、ファイル更新時刻が変わらない限り、ファイルの解析とコードオブジェクトのコンパイルは、インタプリタごとに一度しか行いません。
キャッシュされたページのサイズが時としてかなりのメモリを消費することがあるため、キャッシュのサイズは 512 ページに制限されています。 メモリの消費量が問題になる場合は、 dbm によるファイルキャッシュに切替えられます。 bsd db を使った簡単なテストでは、速度はわずか 20% しか低下しませんでした。 dbm ライブラリによっては、レコードエントリのサイズに制限を課しているために利用できないことがあります。そのため、自分のシステムで、
anydbm
のデフォルトの実装が何かを調べておく必要があるでしょう。 dbm によるキャッシュは mod_python のオプションmod_python.psp.cache_database_filename
で有効にします:PythonOption mod_python.psp.cache_database_filename "/tmp/pspcache.dbm"
dbm キャッシュファイルは、サーバの再起動しても削除されないので注意してください。
ファイルと違い、文字列から生成したコードオブジェクトはメモリ上にしかキャッシュされません。 現時点では、dbm ファイル上にキャッシュするという選択肢はありません。
上のオプション名が現在の名前になったのは、 mod_python 3.3 からなので注意してください。 以前のバージョンの mod_python との互換性を保ちたければ、
PSPDbmCache
を使ってください。-
run
([vars[, flush]])¶ このメソッドは、 初期化時にPSPソースを解析/コンパイルしてできたコードを実行します。 オプションの引数 vars は文字列をキーにした辞書で、グローバル変数の辞書として渡されます。 オプションの引数 flush はブール値で、出力をフラッシュするかどうかを指定します。 デフォルト値は False で、フラッシュしません。
さらに、PSP コードには
req
,psp
,session
およびform
といったグローバル変数が渡されます。 コード中でsession
を参照している場合に限り、セッション情報が生成され、変数session
に代入されます (PSP ハンドラはコードオブジェクトのco_names
を調べてsession
への参照の有無を判定します)。session
を一度でも参照すると、好むと好まざるとにかかわらずsession
はクッキーを生成してセッションのロックを開始するということを覚えておいてください。 同様に、form
がコード中で参照されていると、mod_python
クラスのFieldStorage
オブジェクトがインスタンス化されます。psp
にはPSPInstance
のインスタンスが渡されます。
-
display_code
()¶ 元の PSP コードと PSP パーザが生成した Python コードのリストを横に並べたような形に HTML でフォーマットし、文字列にして返します。
-
PSP
をテンプレートメカニズムとして使う例を、以下に示します:
テンプレートファイルは以下のようになります:
<html>
<!-- This is a simple psp template called template.html -->
<h1>Hello, <%=what%>!</h1>
</html>
ハンドラコードは以下のようになります:
from mod_python import apache, psp
def handler(req):
template = psp.PSP(req, filename='template.html')
template.run({'what':'world'})
return apache.OK
-
class
psp.
PSPInterface
¶
このクラスのオブジェクトは、グローバル変数 psp
として PSP コードに渡されます。
オブジェクトは内部的にインスタンス化されるので、 __init__()
のインタフェースは意図的にドキュメント化していません。
psp.
set_error_page
(filename)¶例外が生じたときに処理される psp ページを設定するために使います。 filename が絶対パス表記の場合、ドキュメントルートに続くパスとみなします。 それ以外の場合は、現在のページと同じディレクトリにあるものとみなします。 エラーページは
sys.exc_info()
の返す三要素のタプルを引数exception
で受け取ります。
psp.
apply_data
(object[, **kw])¶このメソッドはフォームデータをキーワード引数にして呼び出し可能オブジェクト object を呼び出し、その結果を返します。
psp.
redirect
(location[, permanent=0])¶このメソッドは、ブラウザを location にリダイレクトさせます。 permanent が真の場合、 :const:
MOVED_PERMANENTLY
を送信します(そうでない場合にはMOVED_TEMPORARILY
を送信します)。注釈
リダイレクトを起こせるのはクライアントにデータを送信する前だけです。 従って、このメソッドを呼び出す Python コードブロックはページの先頭になければなりません。 そうでない場合、
IOError
が送出されます。例:
<% # 上の '<' は、この PSP ファイルの先頭の文字であることに注意! psp.redirect('http://www.modpython.org') %>
この他に、 psp
は以下の低水準関数を提供しています:
-
psp.
parse
(filename[, dir])¶ この関数は、名前が filename のファイルを開き、内容を読み出して解析し、得られた Python コードの入った文字列を返します。
dir を指定すると、解析対象となるファイルの完全な名前を dir と filename を使って決定すると同時に、
include
ディレクティブの引数を相対パスとして指定できるようになります。 (ファイル名は単に二つの変数をつなげて作成するため、 dir の末尾にパス区切り文字が入っていなくても補完されないので注意してください。)
-
psp.
parsestring
(string)¶ この関数は string の内容を解析し、得られた Python コードを文字列で返します。
httpdconf
– HTTPd Configuration¶
The httpdconf
module provides a simple framework for generating
Apache HTTP Server configuration in Python. It was inspired by HTMLgen
by Robin Friedrich. httpdconf
appeared in 2002 as part of the
mod_python test framework and its use has been primarily limited to
mod_python tests. This latest version of mod_python includes many
improvements to httpdconf
and makes it part of the Python API.
The basic idea is that an Apache configuration directive can be specified as Python code, e.g.:
>>> from mod_python.httpdconf import *
>>> conf = DocumentRoot('/path/to/htdocs')
The resulting object renders itself as a valid Apache directive when converted to string:
>>> print conf
DocumentRoot /path/to/htdocs
While the __repr__
method of the object returns the string of
Python code used to construct it in the first place:
>>> print `conf`
DocumentRoot('/path/to/htdocs')
Classes for Directive types¶
httpdconf
separates all Apache directives into the following
classes.
-
class
httpdconf.
Directive
(name, value[, flipslash=1])¶ This is a simple directive. Its syntax is the directive name followed by a string value. Even though the Apache directives can be followed by multiple arguments,
httpdconf
views it as just a single string, e.g.CustomLog('logs/access_log combined')
.
-
class
httpdconf.
Container
(*args[, only_if=None])¶ A Container groups directives specified as args into a single object. args can include other containers as well. The optional only_if argument is a string of Python that is evaled at directive render time. The directive is rendered only if the eval return a true value.
>>> c = Container(CustomLog('logs/access_log combined'), ErrorLog('logs/error_log')) >>> print c CustomLog logs/access_log combined ErrorLog logs/error_log
>>> print `c` Container( CustomLog('logs/access_log combined'), ErrorLog('logs/error_log'), only_if='True') )
Note how elements within a Container are properly indented when rendered as Python code. A more practical example of only_if may be
only_if="mod_python.version.HTTPD_VERSION[0:3] == '2.4'"
.-
append
(value)¶ Appends an object to a container. There is no difference between specifying contained object at creation time or appending elements to a container later.
-
-
ContainerTag(tag, attr, args[, flipslash=1)]
A ContainerTag is a tag that contains other tags, e.g.
Directory
orLocation
.
-
class
httpdconf.
Comment
(comment)¶ A Comment renders itself as an Apache configuration comment. There is no need to include
#
as part of the comment string. Multi-line comments can be specified by a newline charater. Example:>>> c = Comment("\nThis is\na comment\n") >>> print c # # This is # a comment >>> print `c` Comment('\n' 'This is\n' 'a comment\n')
httpdconf
includes a basic set of Apache configuration
directives (see code for which ones), but any Apache configuration
directive can be trivially created by sub-classing one of the above
classes:
>>> from mod_python.httpdconf import *
>>> class MyDirective(Directive):
... def __init__(self, val):
... Directive.__init__(self, self.__class__.__name__, val)
...
>>> c = MyDirective('foo')
>>> print c
MyDirective foo
Apache設定ディレクティブ¶
リクエストハンドラ¶
Python*Handlerディレクティブの構文¶
リクエストハンドラのディレクティブは、全て次のような構文です:
Python*Handler handler [handler ...] [ | .ext [.ext ...] ]
handler は呼び出し可能オブジェクトで、単一の引数、リクエストオブジェクトをとります。 .ext はファイルの拡張子です。
一つの行には複数のハンドラを指定できます。 複数指定すると、ハンドラを左から右へ順に呼びます。 同じハンドラの設定を繰り返して指定でき、同じ結果になります。 すなわち、全てのハンドラが最初から最後まで順次実行されます。
ハンドラ列のうちいずれかが apache.OK
または apache.DECLINED
以外の値を返すと、それ以降のハンドラの実行を中止します。
ハンドラが apache.OK
や apache.DECLINED
すと何が起きるかは、処理フェイズによって異なります。
mod_python 3.3 以前は、リクエストの処理フェイズに関係なく、ハンドラのいずれかが apache.OK
以外の値を返すと、その時点でフェイズの処理を中断していました。
ハンドラリストの後ろには、 |
を続け、その後ろにファイル拡張子を複数個指定できます。
この指定を行うと、該当するファイル拡張子に対してのみ、ハンドラが実行されるよう制限します。
この機能は trans フェイズ後に実行されるハンドラにのみ作用します。
ハンドラ の構文は、以下の通りです:
module[::object]
module は完全なモジュール名 (パッケージ名のドット表記も利用できます) か、モジュールコードのファイルの実際のパスです。
モジュールは mod_python のモジュール import 機構、 apache.import_module()
で読み込まれます。
モジュールの import 方法について詳しく知りたければ、この関数のドキュメントを参照してください。
オプションの object はモジュール内のオブジェクト名です。
オブジェクトの指定にもドット(.)を含められます。
ドットを含める場合、左から右に名前解決を行ってゆきます。
解決処理中に <class>
型のオブジェクトに遭遇すると、 mod_python はリクエストオブジェクトを引数にしてクラスのインスタンスを生成しようとします。
オブジェクト名を指定しない場合、ハンドラのディレクティブ名をすべて小文字にして、先頭の python
を除いた名前をデフォルトとして使います。
例えば、 PythonAuthenHandler
に対するデフォルトのオブジェクト名は authenhandler
です。
例:
PythonAuthzHandler mypackage.mymodule::checkallowed
ハンドラの詳細については「 Overview of a Request Handler 」を参照してください。
注釈
::
を使っているのは、パフォーマンス上の理由からです。
Python は、モジュール内のオブジェクトを使用する場合、まず最初にモジュールを import しておく必要があります。
区切りを単に .
にしてしまうと、区切った語が、それぞれパッケージ、モジュール、クラスなどのどれにあたるかを順に評価していくプロセスがかなり複雑になってしまいます。
そこで、(Pythonらしくない) ::
を使うことで、モジュールを指定する部分がどこで終わり、モジュール内のオブジェクトの指定がどこから始まるのかを判定するためのオーバヘッド mod_python から省き、パフォーマンスをそこそこ稼いでいます。
このドキュメントの各ハンドラは、Apache が各フェイズで呼び出す順番に並んでいます。
Python*Handlers と Python のモジュールサーチパス¶
Python*Handler
ディレクティブを ディレクトリセクション (<Directory></Directory>
や <DirectoryMatch></DirectoryMatch>
の中、または .htaccess
ファイルの中) で使うと、そのディレクトリは自動的に Python モジュールサーチパス (sys.path
) の先頭に付加されます。 ただし 、 PythonPath
を明に設定した場合は別です。
Python*Handler
ディレクティブを ロケーションセクション (<Location></Location>
や <LocationMatch></LocationMatch>
の中) で使った場合には、モジュールパスは変更されないので、ハンドラモジュールを読み込むためにパスを設定したい場合などには PythonPath
ディレクティブが必要です。
また、ロケーションセクション中で Python*Handlers
を使うと、 mod_python は、 URI からファイルへのマッピングを行なうリクエスト処理フェイズ (ap_hook_map_to_storage
) のハンドラを無効にします。
なぜなら、通常は <Location>
とファイルシステムにはリンクがない上に、ファイルシステム上からファイルを探して対応付けるために、不要で実行コストの大きいファイルシステムコールが発生するからです。
この仕様の重要な副作用として、リクエストが mod_python のハンドラが定義された <Location>
にマッチすると、そのリクエストの以降の処理では、 <Directory>
や <DirectoryMatch>
ディレクティブとその内容は無視されるということにも注意してください。
PythonPostReadRequestHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host
オーバライド: not None
モジュール: mod_python.c
このハンドラは、Apacheがリクエストの内容を読み込み終わった後で、かつ、他のフェイズの処理が行われるよりも前に呼び出されます。 このハンドラは入力ヘッダフィールドに基づいて何らかの判定を行う場合に便利です。
複数のハンドラを指定した場合、いずれかのハンドラが
apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
注釈
このリクエスト処理フェイズでは、URI はまだパス名に変換されていません。
従って、 <Directory>
や <Location>
、 <File>
といったディレクティブの中や .htaccess
ファイルの中でこのディレクティブを指定しても Apache は設定値を使えません。
このディレクティブを置けるのはメインの設定ファイルのみで、そのコードはメインのインタプリタが実行します。
また、このフェイズはリクエストのコンテキストタイプ (例えば、要求が Python プログラムを指しているのか、それとも gif ファイルなのか) を特定するよりも前に発生するので、このハンドラで指定した Python のルーチンは、このサーバに対する、 (Pythonプログラム以外も含む) あらゆる リクエストに対して呼び出されてしまいます。
このことは、パフォーマンスが優先課題の場合には充分考慮してください。
PythonTransHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host
オーバライド: not None
モジュール: mod_python.c
このハンドラは、元のリクエストの URI を、 Apache がデフォルトの規則で (Alias ディレクティブなどの効果によって) 書き換えてしまうより前に、 URI から実際のファイル名を切り出したりするのに使えます。
複数のハンドラを指定した場合、ハンドラのいずれかが apache.DECLINED
以外の値を返すと、それ以降のハンドラの実行を停止します。
注釈
このリクエスト処理フェイズでは、URI はまだパス名に変換されていません。
従って、 <Directory>
や <Location>
、 <File>
といったディレクティブの中や、 .htaccess
ファイルの中で指定しても、 Apache はこのディレクティブを実行できません。
このディレクティブを置けるのはメインの設定ファイルのみで、
そのコードはメインのインタプリタが実行します。
PythonHeaderParserHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このハンドラは、リクエスト処理の早期に、モジュールがリクエストヘッダを調べて、何らかの適切な動作を行うチャンスを設けるために呼び出されます。
複数のハンドラを指定した場合、いずれかのハンドラが
apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
PythonInitHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
リクエスト処理フェイズの中で最初に呼び出されるハンドラで、 .htaccess
とディレクトリの内外で使用できます。
複数のハンドラを指定した場合、いずれかのハンドラが apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
このハンドラは、実際には異なる2つのハンドラの別名です。
メイン設定ファイル中でディレクトリタグの外に設定したときは、 PostReadRequestHandler
の別名です。
ディレクトリタグの内側 (PostReadRequestHandler
を置けない) に設定したときには、 PythonHeaderParserHandler
の別名です。
*(このアイデアはmod_perlをもとにしています)*
PythonAccessHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このルーチンは、リクエストされたリソースに対し、モジュールでアクセス制限をかけるのに使われます。
複数のハンドラを指定した場合、いずれかのハンドラが apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
例えば、このハンドラを使って、 IP アドレスによる制限を行えます。
アクセス不許可を示したければ、このハンドラで HTTP_FORBIDDEN
などを返します。
PythonAuthenHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このハンドラは、認証情報をチェックするときに呼ばれます。 認証情報は、リクエストと同時に送信されてきます。 送られてきた認証情報を、ユーザがデータベースの中にあるかどうか、また [暗号化された] パスワードが、データベース上のパスワードと一致しているかを調べるなどしてチェックしてください。
複数のハンドラを指定した場合、いずれかのハンドラが apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
ユーザ名を得るには、 req.user
を使ってください。
また、ユーザが入力したパスワードを得るには req.get_basic_auth_pw()
関数を使ってください。
apache.OK
を返すと、認証が成功したことを意味します。
apache.HTTP_UNAUTHORIZED
を返すと、大抵のブラウザは認証ダイアログ (パスワード入力ダイアログ) を再表示します。
apache.HTTP_FORBIDDEN
を返すと、ブラウザはエラーを表示し、認証(パスワード)ダイアログを表示しません。
認証に成功しても、ユーザが特定のURLにアクセスできないような場合には、 HTTP_FORBIDDEN
を使ってください。
認証ハンドラの例は以下のようになります:
def authenhandler(req):
pw = req.get_basic_auth_pw()
user = req.user
if user == "spam" and pw == "eggs":
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
注釈
req.get_basic_auth_pw()
は req.user()
の値を使う前に呼び出さねばなりません。
Apacheは req.get_basic_auth_pw()
を呼び出すまで、認証情報のデコードを試みません。
PythonAuthzHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このハンドラは AuthenHandler
の後に実行されます。
このハンドラは、ユーザが特定のリソースにアクセスできるかどうかを調べるときに使います。
とはいえ、その処理を AuthenHandler
中で完結してしまう場合もよくあります。
複数のハンドラを指定した場合、いずれかのハンドラが apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
PythonTypeHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このルーチンは、様々なドキュメントタイプ情報を決定したり設定したりするために呼び出されます。
ドキュメントタイプ情報とは、 (r->content_type
で判る) Content-type や、言語などです。
複数のハンドラを指定した場合、いずれかのハンドラが apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
PythonFixupHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このハンドラは、ヘッダフィールドの特別な修正などを行なうのに使います。 コンテンツハンドラの直前に呼び出されます。
複数のハンドラを指定した場合、いずれかのハンドラが apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
PythonHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
メインのリクエストハンドラです。 多くのアプリケーションではこのハンドラだけを指定することになるでしょう。
複数のハンドラを指定した場合、いずれかのハンドラが apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行せず、その戻り値をコンテンツハンドラフェーズ全体の戻り値にします。
最終的に戻り値が apache.DECLINED
だった場合、Apache はデフォルトハンドラへのフォールバックを試み、リクエストを静的ファイルの要求として処理しようとします。
PythonLogHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
このルーチンはモジュール固有のログ関連の処理を行なうために呼び出されます。
複数のハンドラを指定した場合、いずれかのハンドラが apache.OK
や apache.DECLINED
以外の値を返すと、それ以降のハンドラはこのフェイズでは実行しません。
PythonCleanupHandler¶
書式: Python*Handler Syntax
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
一番最後のハンドラで、Apache がリクエストオブジェクトを捨てる直前に呼ばれます。
他のハンドラと違い、戻り値は無視されます。
エラーはエラーログに書きこまれますが、 PythonDebug
が On
になっていても、クライアントには何も送信しません。
このハンドラは rec.add_handler()
関数の引数には使えません。
動的に後処理 (cleanup) を登録したければ、あらかじめ req.register_cleanup()
を使っておいてください。
一度後処理が始まると、それ以上後処理は登録できません。
そのため、 req.register_cleanup()
はこのハンドラ内では効果がありません。
このディレクティブで登録したハンドラは、 req.register_cleanup()
で
登録した後処理ハンドラよりも 後 に実行されます。
フィルタ¶
PythonInputFilter¶
書式: PythonInputFilter handler name
コンテキスト: server config
モジュール: mod_python.c
name という名前で入力フィルタ handler を登録します。
Handler はモジュール名で、 ::
のあとに続けて呼出し可能オブジェクトの名前を指定できます。
呼出し可能オブジェクトの名前を省略した場合、デフォルト値の inputfilter
になります。
慣例で、 name に登録するフィルタ名は大抵は全て大文字にします。
handler で参照する モジュール は、完全なモジュール名にできます (パッケージのドット表記を使えます)。
また、モジュールのコードが書かれたファイルの実際のパスでもかまいません。
モジュールは mod_python のモジュールインポート機構である apache.import_module()
がロードします。
モジュールをインポートするメカニズムを詳しく知りたければ、 apache.import_module()
のドキュメントを参照してください。
フィルタを有効にするには AddInputFilter
を設定します。
PythonOutputFilter¶
書式: PythonOutputFilter handler name
コンテキスト: server config
モジュール: mod_python.c
name という名前で出力フィルタ handler を登録します。
Handler はモジュール名で、 ::
のあとに続けて呼出し可能オブジェクト名をつけられます。
呼出し可能オブジェクトの名前を省略した場合、デフォルト値の outputfilter
になります。
慣例で Name に登録するフィルタ名は大抵は全て大文字にします。
handler で参照する モジュール は、完全なモジュール名にできます (パッケージのドット表記を使えます)。
また、モジュールのコードが書かれたファイルの実際のパスでもかまいません。
モジュールは mod_python のモジュールインポート機構である apache.import_module()
がロードします。
モジュールをインポートするメカニズムを詳しく知りたければ、 apache.import_module()
のドキュメントを参照してください。
フィルタを有効にするには AddOutputFilter
を設定します。
接続ハンドラ¶
PythonConnectionHandler¶
書式: PythonConnectionHandler handler
コンテキスト: server config
モジュール: mod_python.c
接続を接続ハンドラ*handler* で処理するよう指定します。 Handler には単一の引数、接続オブジェクトが渡されます。
*Handler*はモジュール名で、
::
のあとに続けて呼出し可能オブジェクト名をつけられます。
呼出し可能オブジェクトの名前を省略した場合、デフォルトで connectionhandler
になります。
handler で参照する モジュール は、完全なモジュール名にできます (パッケージのドット表記を使えます)。
また、モジュールのコードが書かれたファイルの実際のパスでもかまいません。
モジュールは mod_python のモジュールインポート機構である apache.import_module()
がロードします。
モジュールをインポートするメカニズムを詳しく知りたければ、 apache.import_module()
のドキュメントを参照してください。
その他のディレクティブ¶
PythonEnablePdb¶
書式: PythonEnablePdb {On, Off}
Default: PythonEnablePdb Off
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
On
の場合、 mod_python
は pdb.runcall()
関数を使って、 Pythonデバッガ pdb
の下でハンドラを実行します。
pdb
は対話的なツールなので、このディレクティブを使う場合には -DONE_PROCESS
オプション付きで httpd を起動してください。
ハンドラコードに到達すると、すぐに pdb のプロンプトが表示され、コードをステップごとに進めて変数を調べられるはずです。
PythonDebug¶
書式: PythonDebug {On, Off}
Default: PythonDebug Off
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
通常、Python のエラーが捕捉されずに上がってくると、トレースバック出力はログに送られます。
PythonDebug を On に設定すると、 IOError
が出るまでは、トレースバックの出力は (ログの他に) クライアントにも送信されます。
ただし、出力時の IOError
の場合にはエラーログだけに送信されます。
このディレクティブは開発時に非常に有用です。 しかし、このディレクティブを使うと、意に反した、場合によっては重大なセキュリティ上の 情報をクライアントに暴露してしまう恐れがあるので、実運用では使わないよう勧めます。
PythonImport¶
書式: PythonImport module interpreter_name
コンテキスト: server config
モジュール: mod_python.c
interpreter_name
に指定した名前を持つインタプリタの下で Python モジュール module
を import するよう、サーバに指示します。
import は子プロセスの初期化時に起こるので、実際には起動した子プロセスあたり一度だけモジュールの import が起こります。
handler で参照する モジュール は、完全なモジュール名にできます (パッケージのドット表記を使えます)。
また、モジュールのコードが書かれたファイルの実際のパスでもかまいません。
モジュールは mod_python のモジュールインポート機構である apache.import_module()
がロードします。
モジュールをインポートするメカニズムを詳しく知りたければ、 apache.import_module()
のドキュメントを参照してください。
PythonImport
は、例えば、データベース接続の初期化など、時間がかかり、リクエスト処理時に実行するのが望ましくない初期化タスクに便利です。
初期化のコードが失敗することがあり、それによってモジュールのインポートが失敗する場合は、関数名を指定したもう一つの書き方を使ってください:
PythonImport *module::function* *interpreter_name*
ここに指定した関数は、モジュールが正しくインポートされた時にのみ実行されます。 関数は引数なしで呼びだされます。
注釈
モジュールのインポートが起きるとき、設定は完全に読み込まれてはいないため、 PythonInterpreter を含む他のどのディレクティブも、このディレクティブでインポートするモジュールに影響を及ぼせません。
この制約があるので、インタプリタ名を明示的に指定しておいて、後のリクエスト処理の仮定で、ここでの処理結果に依存した操作をするときに、名前の一致するインタプリタが使われるようにせねばならないのです。
どんな名前のインタプリタでリクエストを処理しているかわからないときは、リクエストオブジェクトの request.interpreter
メンバを調べてください。
多重インタプリタ (Multiple Interpreters) の節も参照して下さい。
PythonInterpPerDirectory¶
書式: PythonInterpPerDirectory {On, Off}
Default: PythonInterpPerDirectory Off
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
インタプリタの名前を、サーバ名からではなく、リクエスト中のファイルのディレクトリ名(req.filename
) からつけるよう、 mod_python
に指示します。
その結果、デフォルトポリシの場合と違って、二つのスクリプトが別々のディレクトリに置かれていると、それらが互いに別個のサブインタプリタで実行されます。
デフォルトポリシでは、同じ仮想サーバ上のあるスクリプトは、同じサブリンタプリタで実行されます。
- 例えば、
/directory/subdirectory
があると仮定します。/directory
には、PythonHandler
ディレクティブの定義された.htaccess
ファイルがあり、/directory/subdirectory
には.htaccess
がないとします。 /directory
の下のスクリプトと/directory/subdirectory
の下のスクリプトは、同じ仮想サーバを介してアクセスされていれば、同じインタプリタ下で実行されます。
PythonInterpPerDirectory
が有効な場合は各ディレクトリ毎に別個の二つのインタプリタになります。
注釈
URIの変換より前の早い段階のリクエスト処理フェイズ (PostReadRequestHandlerやTransHandler) では、URIがまだ変換されていないため、パスがまだ決まっていません。 その間は、PythonInterpPerDirectoryがOnであったとしても、ハンドラはメインのインタプリタによって実行されます。 この動作は期待にそぐわないかもしれませんが、残念ながら回避する方法はありません。
参考
- Multiple Interpreters
- for more information
PythonInterpPerDirective¶
書式: PythonInterpPerDirective {On, Off}
Default: PythonInterpPerDirective Off
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
サブインタプリタの名前をつけるよう mod_python
に指示します。
名前は、有効な Python*Handler ディレクティブのあるディレクトリの名前になります。
例えば、 /directory/subdirectory
があると仮定します。
/directory
にはPythonHandlerディレクティブの入った .htaccess
ファイルがあり、 /directory/subdirectory
には別の PythonHandler の入った .htaccess
ファイルがあるとします。
デフォルトでは、同じ仮想サーバを介してアクセスされていれば、 /directory
の下のスクリプトと /directory/subdirectory
の下のスクリプトは同じインタプリタ下で実行されます。
PythonInterpPerDirective
が有効な場合、各ディレクティブ毎に別個の二つのインタプリタになります。
参考
- seetitle[pyapi-interps.html]{ref{pyapi-interps} 節、複数のインタプリタ}
- {詳しい情報です}
- Multiple Interpreters
- for more information
PythonInterpreter¶
書式: PythonInterpreter name
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
インタプリタの名前を強制的に name にするよう mod_python
に指示します。
デフォルトの仕様や、 dir-other-ipd`および :ref:`dir-other-ipdv ディレクティブで設定した名前をオーバライドします。
このディレクティブを使うと、通常なら別々のサブインタプリタ下で行われるスクリプトの実行を、同じサブインタプリタ下で行えます。 DocumentRoot の下で使うと、サーバ全体で一つのサブインタプリタを使うようになります。
参考
- Multiple Interpreters
- 詳しい説明です。
PythonHandlerModule¶
書式: PythonHandlerModule module
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
PythonHandlerModule は、他の Python*Handler ディレクティブの代わりとして使えます。 このハンドラでモジュールを指定すると、各種ハンドラ関数を探すときのデフォルトの検索対象モジュールとして使われ、このモジュール中に関数があればそれを実行します。
例えば以下のような設定は:
PythonAuthenHandler mymodule
PythonHandler mymodule
PythonLogHandler mymodule
このように単純に書けます。:
PythonHandlerModule mymodule
PythonAutoReload¶
書式: PythonAutoReload {On, Off}
Default: PythonAutoReload On
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
Off
にセットすると、モジュールファイルの更新日時を調べないよう mod_python
に指示します。
デフォルトでは、 mod_python
はファイルのタイムタンプをチェックし、以前のインポート、またはリロード時よりモジュールファイルの更新時刻が新しければ、そのモジュールをリロードします。
この仕組みでモジュールを自動的に再 import するので、モジュールを更新するたびにサーバーを再起動させる必要が無くなります。
自動リロードを無効化は、モジュールの変化がないプロダクション環境で便利です。 いくらか処理時間を節約でき、わずかなパフォーマンス向上をもたらすからです。
PythonOptimize¶
書式: PythonOptimize {On, Off}
Default: PythonOptimize Off
コンテキスト: server config
モジュール: mod_python.c
Pythonの最適化を有効にします。Pythonの -O
オプションと同じです。
PythonOption¶
書式: PythonOption key [value]
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
キーと値のペアをテーブルに保存して、あとで request.get_options()
で取り出せるようにします。
設定ファイル ( httpd.conf
や .htaccess
など) と、Pythonプログラムの間で情報を受け渡すのに便利です。
値を省略したり空文字 (""
) にすると、そのキーを設定から除去します。
予約済の PythonOption キーワード¶
PythonOption
で指定できるキーワードの中には、 mod_python の様々な動作を設定するのに使われているものがあります。 mod_python.* で始まるキーワードは予約済みで、 mod_python の中で使うことを想定しています。
ユーザは、自分のアドオンモジュールを作る際、独自の名前空間を使って、決してグローバルの名前空間を使わないようにしましょう。
以下の PythonOption は、実際に mod_python で使われています。
PythonPath¶
書式: PythonPath path
コンテキスト: server config, virtual host, directory, htaccess
オーバライド: not None
モジュール: mod_python.c
PythonPath ディレクティブは、 PythonPath をセットします。 パスはPython のリスト表記で指定せねばなりません:
PythonPath "['/usr/local/lib/python2.0', '/usr/local/lib/site_python', '/some/other/place']"
このディレクティブで設定したパスは、既存のパスへの追加ではなく、置き換えになります。
ただし、パスの指定値は eval
で評価されるので、ディレクトリを追加したければ、以下のように指定できます:
PythonPath "sys.path+['/mydir']"
mod_python
は PythonPath ディレクティブに関係する eval の実行回数を最低限にしようと試みます。というのも、 eval は低速で、とりわけ、 .htaccess
ファイル内で指定すると毎回ヒットするたびに評価されるので、強烈な悪影響を及ぼすことがあるからです。
mod_python
はPythonPathディレクティブの引数 (評価する前の状態) を覚えておき、値を評価する前に覚えておいた値と比較して、値が同じならば何も行いません。
そのため、コード内で sys.path を変更している場合、このディレクティブがパスの内容を元に戻す手段になるなどと当てにしてはなりません。
PythonPath ディレクティブを複数回指定しても、効果が足し合わされたりはせず、最後に指定したディレクティブが以前のディレクティブの設定を上書きします。
注釈
このディレクティブをセキュリティ対策に使ってはなりません。 Pythonパスはスクリプトで簡単に操作できるからです。
標準ハンドラ¶
Publisher ハンドラ¶
publisher
ハンドラを使えば、わざわざ自分でハンドラを書く必要がなく、素早いアプリケーション開発に専念できます。
publisher
ハンドラは、 Zope の ZPublisher から着想を得ています。
はじめに¶
ハンドラを使うには、設定ファイルに以下のように書きます:
<Directory /some/path>
SetHandler mod_python
PythonHandler mod_python.publisher
</Directory>
このハンドラを使うと、モジュール内の関数や変数を URL でアクセスできます。
例えば、 hello.py
という名の以下のようなモジュールがあるとしましょう:
""" Publisher example """
def say(req, what="NOTHING"):
return "I am saying %s" % what
これで、 http://www.mysite.com/hello.py/say
という URL は I am saying NOTHING
を返します。
一方、 http://www.mysite.com/hello.py/say?what=hello
は I am saying hello
を返します。
パブリッシュのアルゴリズム¶
publisher ハンドラは URI を Python の変数や呼び出し可能オブジェクトに直接対応づけます。 変数の場合には文字列表現を、呼び出しオブジェクトの場合には呼び出した戻り値の文字列表現を返します。
トラバース¶
publisher ハンドラは、 URI に指定したモジュールを探して import します。
モジュールの位置は request.filename
属性で決まります。
import の際、ファイル拡張子がある場合には無視します。
request.filename
が空の場合には、 'index'
をデフォルト値のモジュール名として使います。
モジュールを import すると、URI の残りの部分からクエリデータまで (いわゆる PATH_INFO
) の部分を使って、モジュール内のオブジェクトを探します。
publisher ハンドラは各要素をモジュール内のPython オブジェクトに対応づけながら、パスの要素を左から右にひとつづつ トラバース します。
URL に PATH_INFO
がない場合、publisher ハンドラは index
をデフォルト値に使います。
パスの最後の要素がモジュール内のオブジェクト名で、かつその前にある要素がディレクトリ名の場合 (モジュール名が指定されていない場合)、モジュール名はデフォルト値の index
になります。
以下のような場合にはトラバースを停止して HTTP_NOT_FOUND
を返します:
- トラバースしたオブジェクトの名前がアンダースコア (
_
) で始まっている場合。 逆に、Web からアクセスさせたくないオブジェクトを保護するにはアンダースコアを使ってください。 - モジュールに到達した場合。セキュリティ上の理由から、モジュールはパブリッシュの対象にできません。
パス上にオブジェクトが見つからなかった場合、クライアントに HTTP_NOT_FOUND
を返します。
例えば、以下のような設定があるとしましょう:
DocumentRoot /some/dir
<Directory /some/dir>
SetHandler mod_python
PythonHandler mod_python.publisher
</Directory>
そして、以下のようなファイル /some/dir/index.py
があったとします:
def index(req):
return "We are in index()"
def hello(req):
return "We are in hello()"
URL にアクセスした結果は次のようになります:
- http://www.somehost/index/index は
'We are in index()'
を返します。 - http://www.somehost/index/ は
'We are in index()'
を返します。 - http://www.somehost/index/hello は
'We are in hello()'
を返します。 - http://www.somehost/hello は
'We are in hello()'
を返します。 - http://www.somehost/spam は
'404 Not Found'
を返します。
引数のマッチングと呼び出し¶
publisher ハンドラがパブリッシュ対象のオブジェクトを見つけたとします。
オブジェクトが呼び出し可能オブジェクトであってクラスでない場合、ハンドラはオブジェクトの受け取る引数のリストを調べます。
次に、このリストを POST
や GET
経由で受け取ったフォームデータのパラメタ名と比較します。
引数と名前の一致するフィールドの値は、呼び出し可能オブジェクトの該当する引数に文字列で渡します。
名前の一致しないフィールドは暗黙のまま捨てます。ただし、対象のオブジェクトが **kwargs
形式の引数を受け取る場合には、名前の一致しなかったフィールドを **kwargs
引数で渡します。
パブリッシュ対象のオブジェクトが呼び出し可能オブジェクトの場合やクラスの場合、その文字列表現をクライアントに返します。
Authentication¶
The publisher handler provides simple ways to control access to modules and functions.
At every traversal step, the Publisher handler checks for presence of
__auth__
and __access__
attributes (in this order), as
well as __auth_realm__
attribute.
If __auth__
is found and it is callable, it will be called
with three arguments: the request
object, a string containing
the user name and a string containing the password. If the return
value of
__auth__
is false, then HTTP_UNAUTHORIZED
is
returned to the client (which will usually cause a password dialog box
to appear).
If __auth__()
is a dictionary, then the user name will be
matched against the key and the password against the value associated
with this key. If the key and password do not match,
HTTP_UNAUTHORIZED
is returned. Note that this requires
storing passwords as clear text in source code, which is not very secure.
__auth__
can also be a constant. In this case, if it is false
(i.e. None
, 0
, ""
, etc.), then
HTTP_UNAUTHORIZED
is returned.
If there exists an __auth_realm__
string, it will be sent
to the client as Authorization Realm (this is the text that usually
appears at the top of the password dialog box).
If __access__
is found and it is callable, it will be called
with two arguments: the request
object and a string containing
the user name. If the return value of __access__
is false, then
HTTP_FORBIDDEN
is returned to the client.
If __access__
is a list, then the user name will be matched
against the list elements. If the user name is not in the list,
HTTP_FORBIDDEN
is returned.
Similarly to __auth__
, __access__
can be a constant.
In the example below, only user 'eggs'
with password 'spam'
can access the hello
function::
__auth_realm__ = "Members only"
def __auth__(req, user, passwd):
if user == "eggs" and passwd == "spam" or \
user == "joe" and passwd == "eoj":
return 1
else:
return 0
def __access__(req, user):
if user == "eggs":
return 1
else:
return 0
def hello(req):
return "hello"
Here is the same functionality, but using an alternative technique::
__auth_realm__ = "Members only"
__auth__ = {"eggs":"spam", "joe":"eoj"}
__access__ = ["eggs"]
def hello(req):
return "hello"
Since functions cannot be assigned attributes, to protect a function,
an __auth__
or __access__
function can be defined within
the function, e.g.::
def sensitive(req):
def __auth__(req, user, password):
if user == 'spam' and password == 'eggs':
# let them in
return 1
else:
# no access
return 0
# something involving sensitive information
return 'sensitive information`
Note that this technique will also work if __auth__
or
__access__
is a constant, but will not work is they are
a dictionary or a list.
The __auth__
and __access__
mechanisms exist
independently of the standard
PythonAuthenHandler. It
is possible to use, for example, the handler to authenticate, then the
__access__
list to verify that the authenticated user is
allowed to a particular function.
注釈
In order for mod_python to access __auth__
, the module
containing it must first be imported. Therefore, any module-level
code will get executed during the import even if
__auth__
is false. To truly protect a module from being
accessed, use other authentication mechanisms, e.g. the Apache
mod_auth
or with a mod_python PythonAuthenHandler.
Form Data¶
In the process of matching arguments, the Publisher handler creates an
instance of FieldStorage class.
A reference to this instance is stored in an attribute member{form}
of the request
object.
Since a FieldStorage
can only be instantiated once per
request, one must not attempt to instantiate FieldStorage
when
using the Publisher handler and should use
request.form
instead.
WSGI Handler¶
WSGI handler can run WSGI applications as described in PEP 333.
Assuming there exists the following minimal WSGI app residing in a file named
mysite/wsgi.py
in directory /path/to/mysite
(so that the full
path to wsgi.py
is /path/to/mysite/mysite/wsgi.py
):
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
It can be executed using the WSGI handler by adding the following to the Apache configuration:
PythonHandler mod_python.wsgi
PythonOption mod_python.wsgi.application mysite.wsgi
PythonPath "sys.path+['/path/to/mysite']"
The above configuration will import a module named mysite.wsgi
and
will look for an application
callable in the module.
An alternative name for the callable can be specified by appending it
to the module name separated by '::'
, e.g.:
PythonOption mod_python.wsgi.application mysite.wsgi::my_application
If you would like your application to appear under a base URI, it can
be specified by wrapping your configuration in a <Location>
block. It can also be specified via the mod_python.wsgi.base_uri
option, but the <Location>
method is recommended, also because it
has a side-benefit of informing mod_python to skip the map-to-storage
processing phase and thereby improving performance.
For example, if you would like the above application to appear under
'/wsgiapps'
, you could specify:
<Location /wsgiapps>
PythonHandler mod_python.wsgi
PythonOption mod_python.wsgi.application mysite.wsgi
PythonPath "sys.path+['/path/to/mysite']"
</Location>
With the above configuration, content formerly under
http://example.com/hello
becomes available under
http://example.com/wsgiapps/hello
.
If both <Location>
and mod_python.wsgi.base_uri
exist, then
mod_python.wsgi.base_uri
takes precedence.
mod_python.wsgi.base_uri
cannot be '/'
or end with a
'/'
. “Root” (or no base_uri) is a blank string, which is the
default. (Note that it is allowed for <Location>
path to be
"/"
or have a trailing slash, it will automatically be removed by
mod_python before computing PATH_INFO
).
注釈
PEP 333 describes SCRIPT_NAME
and PATH_INFO
environment
variables which are core to the specification. Most WSGI-supporting
frameworks currently in existence use the value of PATH_INFO
as the
request URI.
The two variable’s name and function originate in CGI
(RFC 3875), which describes an environment wherein a script (or
any executable’s) output could be passed on by the web server as
content. A typical CGI script resides somewhere on the filesystem
to which the request URI maps. As part of serving the request the
server traverses the URI mapping each element to an element of the
filesystem path to locate the script. Once the script is found, the
portion of the URI used thus far is assigned to the SCRIPT_NAME
variable, while the remainder of the URI gets assigned to
PATH_INFO
.
Because the relationship between Python modules and files on disk
is largely tangential, it is not very clear what exactly
PATH_INFO
and SCRIPT_NAME
ought to be. Even though Python
modules are most often files on disk located somewhere in the
Python path, they don’t have to be (they could be code objects
constructed on-the-fly), and their location in the filesystem has
no relationship to the URL structure at all.
The mismatch between CGI and WSGI results in an ambiguity which
requires that the split between the two variables be explicitely
specified, which is why mod_python.wsgi.base_uri
exists. In essence
mod_python.wsgi.base_uri
(or the path in surrounding
<Location>
) is the SCRIPT_NAME
portion of the URI and
defaults to ''
.
An important detail is that SCRIPT_NAME
+ PATH_INFO
should
result in the original URI (encoding issues aside). Since
SCRIPT_NAME
(in its original CGI definition) referrs to an
actual file, its name never ends with a slash. The slash, if any,
always ends up in PATH_INFO
. E.g. /path/to/myscrip/foo/bar
splits into /path/to/myscript
and /foo/bar
. If the whole
site is served by an app or a script, then SCRIPT_NAME
is a
blank string ''
, not a '/'
.
PSP Handler¶
PSP handler is a handler that processes documents using the
PSP
class in mod_python.psp
module.
To use it, simply add this to your httpd configuration:
AddHandler mod_python .psp
PythonHandler mod_python.psp
For more details on the PSP syntax, see Section psp – Python Server Pager.
If PythonDebug
server configuration is On
, then by
appending an underscore ('_'
) to the end of the url you can get a
nice side-by-side listing of original PSP code and resulting Python
code generated by the psp} module
. This is very useful for
debugging. You’ll need to adjust your httpd configuration::
AddHandler mod_python .psp .psp_
PythonHandler mod_python.psp
PythonDebug On
注釈
Leaving debug on in a production environment will allow remote users to display source code of your PSP pages!
CGI ハンドラ¶
CGI ハンドラは、 mod_python
下で CGI 環境をエミュレートするためのハンドラです。
この環境は、「真の」CGI 環境ではなく、Python レベルのエミュレーションなので注意してください。
この環境では、 stdin
および stdout
は、それぞれ sys.stdin
と sys.stdout
に置き換わり、環境変数は辞書に置き換わります。
そのため、CGI ハンドラの環境から os.system
などで呼び出した外部プログラムは、 Python プログラム側で利用できる環境変数を見られないばかりか、 「真の」 CGI 環境ではできるはずの標準入出力を使った結果の読み書きも行えません。
このハンドラは CGI の古いコードから移行するための飛び石として提供されています。
mod_python
を使う方法として、このハンドラに長く腰を落ち着けるのはお勧めしません。
なぜなら、この環境はスレッド内での実行を想定しておらず、 mod_python
の数多くの利点を最初から台無しにしてしまうような実装しかできないからです
(例えば、CGI の実行には現在のディレクトリの変更が必要ですが、これは本来スレッドセーフな操作ではありません。
cgihandler はこの問題を解決するためにスレッドをロックして、マルチスレッドサーバであっても一度に一つのリクエストしか処理できないようにしてしまいます)。
CGI ハンドラを使いたければ、.htaccess
ファイルに:
SetHandler mod_python
PythonHandler mod_python.cgihandler
のように書くだけです。
バージョン 2.7 からは、 cgihandler は間接的に import されたモジュールも正しくリロードできます。
この機能は、 CGI スクリプトの呼び出し前にロード済みのモジュールのリスト (sys.modules
) を保存しておき、CGI スクリプトを実行した後のリストと比較することで可能にしています。
リロード対象のモジュールは (__file__
属性が標準 Python ライブラリの置き場所を指しているものを除いて) sys.modules
から除去されます。その結果、次に CGI スクリプトがモジュールを import するときに、Python にモジュールをリロードを強制します。
上記の動作を望まないのなら、 cgihandler.py
ファイルを編集して、
###
で区切られているコードをコメントアウトしてください。
テストの結果、 cgihandler は多数のファイルアップロードを処理する際に何らかのメモリリークを起こすことが分かっています。
原因についてはよく分かっていません。この問題を回避するには、 Apache の MaxRequestsPerChild
設定をゼロでない値にしてください。
Command Line Tool - mod_python¶
Overview of mod_python command¶
mod_python includes a command-line tool named mod_python
. The
mod_python
command exists to facilitate tasks related to
configuration and management of mod_python.
The general syntax for the command is mod_python <subcommand> <arguments>
where <subcommand>
is a separate tool with its own argument requirements.
mod_python command line tool sub-commands¶
create¶
create
sub-command creates a simple Apache configuration and a
skeleton directory structure necessary for placement of configuration,
logs and content. It is meant to be executed only once per lifetime of
a project.
The configuration generated by create
consists of an
httpdconf
based version (in Python) which can then be used to
generate an actual Apache configuration (by using the genconfig
subcommand or simply executing the config files itself). The idea is
that the Apache configuration is always generated and the Python
version is the one meant for editing/adjustments.
The create
subcommand will create the necessary files and
directories if they do not exist, but will not overwrite any existing
files or directories only producing a warning when a file or directory
already exists. It will abort if the Python version of the
configuration file already exists.
create
requires a single argument: the distination directory,
Apache ServerRoot
.
create
has the following command options:
-
--listen
¶
A string describing the port and optional IP address on which the server is to listen for incoming requests in the form
[ip_address:]port
The argument will be applied to the ApacheListen
directive as is and therefore must be syntactically compatible with it.
-
--pythonpath
¶
A colon (
":"
) separate list of paths to be applied to the PythonPath directive.
-
--pythonhandler
¶
The name of the Python handler to use. Applied to the PythonHandler directive.
-
--pythonoption
¶
An option to be specified in the configuration. Multiple options are alowed. Applied to the PythonOption directive.
genconfig¶
This sub-command exists to facilitate re-generation of an Apache configuration from a Python-based one. All it does is run the script, but its use is recommended because the mod_python command will execute the correct version of Python under which mod_python was initially compiled. Example:
mod_python genconfig /path/to/server_root/httpd_conf.py > /path/to/server_root/httpd.conf
start¶
Starts an Apache instance. Requires a single argument, the path to Apache configuration file.
stop¶
Stops an Apache instance (using graceful-stop). Requires a single argument, the path to Apache configuration file.
restart¶
Stops an Apache instance (using graceful). Requires a single argument, the path to Apache configuration file.
version¶
This sub-command prints out version and location information about this mod_python installation, the Apache HTTP Server and Python used when building this mod_python instance.
Example¶
To create an Apache instance with all the required directories for a
WSGI application which is located in /path/to/myapp
and defined in
/path/to/myapp/myapp/myapp/wsgi.py
, run the following:
mod_python create /path/to/new/server_root \
--pythonpath=/path/to/my/app \
--pythonhandler=mod_python.wsgi \
--pythonoption="mod_python.wsgi.application myapp.wsgi::application"
The above example will create a Python-based configuration in
/path/to/new/server_root/conf/http_conf.py
which is a simple
Pythong script. When executed, the output of the script becomes an
Apache configuration (create
will take care of generating the
first Apache config for you).
You should be able to run this Apache instance by executing:
mod_python start /path/to/new/server_root/conf/httpd.conf
Server Side Includes¶
Overview of SSI¶
SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology such as a mod_python handler.
SSI directives have the following syntax::
<!--#element attribute=value attribute=value ... -->
It is formatted like an HTML comment, so if you don’t have SSI correctly enabled, the browser will ignore it, but it will still be visible in the HTML source. If you have SSI correctly configured, the directive will be replaced with its results.
For a more thorough description of the SSI mechanism and how to enable it, see the SSI tutorial provided with the Apache documentation.
Version 3.3 of mod_python introduces support for using Python code within
SSI files. Note that mod_python honours the intent of the Apache
IncludesNOEXEC
option to the Options
directive. That is, if
IncludesNOEXEC
is enabled, then Python code within a SSI file will
not be executed.
Using Python Code¶
The extensions to mod_python to allow Python code to be used in conjunction
with SSI introduces the new SSI directive called 'python'
. This directive
can be used in two forms, these being 'eval'
and 'exec'
modes. In the case
of 'eval'
, a Python expression is used and it is the result of that
expression which is substituted in place into the page.:
<!--#python eval="10*'HELLO '" -->
<!--#python eval="len('HELLO')" -->
Where the result of the expression is not a string, the value will be
automatically converted to a string by applying 'str()'
to the value.
In the case of 'exec'
a block of Python code may be included. For any
output from this code to appear in the page, it must be written back
explicitly as being part of the response. As SSI are processed by an Apache
output filter, this is done by using an instance of the mod_python
filter
object which is pushed into the global data set available to
the code.:
<!--#python exec="
filter.write(10*'HELLO ')
filter.write(str(len('HELLO')))
" -->
Any Python code within the 'exec'
block must have a zero first level
indent. You cannot start the code block with an arbitrary level of indent
such that it lines up with any indenting used for surrounding HTML
elements.
Although the mod_python filter
object is not a true file object, that
it provides the write()
method is sufficient to allow the print
statement to be used on it directly. This will avoid the need to explicitly
convert non string objects to a string before being output.:
<!--#python exec="
print >> filter, len('HELLO')
" -->
Scope of Global Data¶
Multiple instances of 'eval'
or 'exec'
code blocks may be used within the
one page. Any changes to or creation of global data which is performed
within one code block will be reflected in any following code blocks.
Global data constitutes variables as well as module imports, function and
class definitions.:
<!--#python exec="
import cgi, time, os
def _escape(object):
return cgi.escape(str(object))
now = time.time()
" -->
<html>
<body>
<pre>
<!--#python eval="_escape(time.asctime(time.localtime(now)))"-->
<!--#python exec="
keys = os.environ.keys()
keys.sort()
for key in keys:
print >> filter, _escape(key),
print >> filter, '=',
print >> filter, _escape(repr(os.environ.get(key)))
" -->
</pre>
</body>
</html>
The lifetime of any global data is for the current request only. If data must persist between requests, it must reside in external modules and as necessary be protected against multithreaded access in the event that a multithreaded Apache MPM is used.
Pre-populating Globals¶
Any Python code which appears within the page has to be compiled each time the page is accessed before it is executed. In other words, the compiled code is not cached between requests. To limit such recompilation and to avoid duplication of common code amongst many pages, it is preferable to pre-populate the global data from within a mod_python handler prior to the page being processed.
In most cases, a fixup handler would be used for this purpose. For this to work, first need to configure Apache so that it knows to call the fixup handler.:
PythonFixupHandler _handlers
The implementation of the fixup handler contained in _handlers.py
then needs to create an instance of a Python dictionary, store that in the
mod_python request object as ssi_globals
and then populate that
dictionary with any data to be available to the Python code executing
within the page.:
from mod_python import apache
import cgi, time
def _escape(object):
return cgi.escape(str(object))
def _header(filter):
print >> filter, '...'
def _footer(filter):
print >> filter, '...'
def fixuphandler(req):
req.ssi_globals = {}
req.ssi_globals['time'] = time
req.ssi_globals['_escape'] = _escape
req.ssi_globals['_header'] = _header
req.ssi_globals['_footer'] = _footer
return apache.OK
This is most useful where it is necessary to insert common information such as headers, footers or menu panes which are dynamically generated into many pages.:
<!--#python exec="
now = time.time()
" -->
<html>
<body>
<!--#python exec="_header(filter)" -->
<pre>
<!--#python eval="_escape(time.asctime(time.localtime(now)))"-->
</pre>
<!--#python exec="_footer(filter)" -->
</body>
</html>
Conditional Expressions¶
SSI allows for some programmability in its own right through the use of conditional expressions. The structure of this conditional construct is::
<!--#if expr="test_condition" -->
<!--#elif expr="test_condition" -->
<!--#else -->
<!--#endif -->
A test condition can be any sort of logical comparison, either comparing values to one another, or testing the ‘truth’ of a particular value.
The source of variables used in conditional expressions is distinct from
the set of global data used by the Python code executed within a page.
Instead, the variables are sourced from the subprocess_env
table
object contained within the request object. The values of these variables
can be set from within a page using the SSI 'set'
directive, or by a range
of other Apache directives within the Apache configuration files such as
BrowserMatchNoCase
and SetEnvIf
.
To set these variables from within a mod_python handler, the
subprocess_env
table object would be manipulated directly through
the request object.:
from mod_python import apache
def fixuphandler(req):
debug = req.get_config().get('PythonDebug', '0')
req.subprocess_env['DEBUG'] = debug
return apache.OK
If being done from within Python code contained within the page itself, the request object would first have to be accessed via the filter object.:
<!--#python exec="
debug = filter.req.get_config().get('PythonDebug', '0')
filter.req.subprocess_env['DEBUG'] = debug
" -->
<html>
<body>
<!--#if expr="${DEBUG} != 0" -->
DEBUG ENABLED
<!--#else -->
DEBUG DISABLED
<!--#endif -->
</body>
</html>
Enabling INCLUDES Filter¶
SSI is traditionally enabled using the AddOutputFilter
directive in
the Apache configuration files. Normally this would be where the request
mapped to a static file.:
AddOutputFilter INCLUDES .shtml
When mod_python is being used, the ability to dynamically enable output
filters for the current request can instead be used. This could be done
just for where the request maps to a static file, but may just as easily be
carried out where the content of a response is generated dynamically. In
either case, to enable SSI for the current request, the
request.add_output_filter()
method of the mod_python request object would be
used.:
from mod_python import apache
def fixuphandler(req):
req.add_output_filter('INCLUDES')
return apache.OK
変更点¶
Changes from version 3.3.1¶
New Features¶
- Create the mod_python command-line tool to report version, manage Apache configuration and instances.
- Make httpdconf directives render themselves as Python, add the only_if conditional and comments.
- Expose and document httpdconf, make mod_python importable outside of Apache.
- Provide a WSGI handler.
- Change the Copyright to reflect the new status.
- Add support for Apache HTTP Server 2.4.
- Add support for Python 2.7.
Improvements¶
- Improve WSGI and Python path documentation.
- Change WSGI handler to use Location path as SCRIPT_NAME.
- Add is_location to hlist object, skip the map_to_storage for Location-wrapped Python*Handlers.
- Some optimizations to Python code to make it run faster.
- Add Mutex to Apache 2.4 tests.
- Provide and internal add_cgi_vars() implementation which does not use sub-requests.
- Many documentation clarifications and improvements.
- Add a test to ensure that req.write() and req.flush() do not leak memory (2.4 only).
- Many new tests and test framework improvements.
- Added a curl hint to the tests for easier stagin/debugging.
- Get rid of the ancient memberlist and PyMember_Get/Set calls.
- Add support for the c.remote_ip/addr to c.client_ip/addr change in 2.4. Add req.useragent_addr (also new in 2.4).
- Always check C version against Py version and warn.
- Remove APLOG_NOERRNO references.
- A more unified and cleaned up method of keeping version information.
- Convert documentation to the new reStructuredText format.
- Revert to using the old importer from 3.2.
- Replace README with README.md
- (MODPYTHON-238) Make req.chunked and req.connection.keepalive writable. Being able to set these allows chunking to be turned off when HTTP/1.1 is used but no content length supplied in response.
- (MODPYTHON-226) Make req.status_line writable.
Bug Fixes¶
- Make PythonCleanupHandler run again.
- Use PCapsule API instead of PyCObject for Python 2.7+.
- Fix SCRIPT_NAME and PATH_INFO inconsistencies so that the WSGI handler behaves correctly.
- Remove with-python-src configure option as it is no longer used to build the docs.
- (MODPYTHON-243) Fixed format string error.
- (MODPYTHON-250) Fixed MacOS X (10.5) Leopard 64 bit architecture problems.
- (MODPYTHON-249) Fixed incorrect use of APR bucket brigades shown up by APR 1.3.2.
- (MODPYTHON-245) Fix prototype of optional exported function mp_release_interpreter().
- (MODPYTHON-220) Fix ‘import’ from same directory as PSP file.
Changes from version 3.2.10¶
New Features¶
- (MODPYTHON-103) New req.add_output_filter(), req.add_input_filter(), req.register_output_fiter(), req.register_input_filter() methods. These allows the dynamic registration of filters and the attaching of filters to the current request.
- (MODPYTHON-104) Support added for using Python in content being passed through “INCLUDES” output filter, or as more commonly referred to server side include (SSI) mechanism.
- (MODPYTHON-108) Added support to cookies for httponly attribute, an extension originally created by Microsoft, but now getting more widespread use in the battle against cross site-scripting attacks.
- (MODPYTHON-118) Now possible using the PythonImport directive to specify the name of a function contained in the module to be called once the designated module has been imported.
- (MODPYTHON-124) New req.auth_name() and req.auth_type() methods. These return the values associated with the AuthName and AuthType directives respectively. The req.ap_auth_type has now also been made writable so that it can be set by an authentication handler.
- (MODPYTHON-130) Added req.set_etag(), req.set_last_modified() and req.update_mtime() functions as wrappers for similar functions provided by Apache C API. These are required to effectively use the req.meets_condition() function. The documentation for req.meets_condition() has also been updated as what it previously described probably wouldn’t actually work.
- (MODPYTHON-132) New req.construct_url() method. Used to construct a fully qualified URI string incorporating correct scheme, server and port.
- (MODPYTHON-144) The “apache.interpreter” and “apache.main_server” attributes have been made publically available. These were previously private and not part of the public API.
- (MODPYTHON-149) Added support for session objects that span domains.
- (MODPYTHON-153) Added req.discard_request_body() function as wrapper for similar function provided by Apache C API. The function tests for and reads any message body in the request, simply discarding whatever it receives.
- (MODPYTHON-164) The req.add_handler(), req.register_input_filter() and req.register_output_filter() methods can now take a direct reference to a callable object as well a string which refers to a module or module::function combination by name.
- (MODPYTHON-165) Exported functions from mod_python module to be used in other third party modules for Apache. The purpose of these functions is to allow those other modules to access the mechanics of how mod_python creates interpreters, thereby allowing other modules to also embed Python and for there not to be a conflict with mod_python.
- (MODPYTHON-170) Added req._request_rec, server._server_rec and conn._conn_rec semi private members for getting accessing to underlying Apache struct as a Python CObject. These can be used for use in implementing SWIG bindings for lower level APIs of Apache. These members should be regarded as experimental and there are no guarantees that they will remain present in this specific form in the future.
- (MODPYTHON-193) Added new attribute available as req.hlist.location. For a handler executed directly as the result of a handler directive within a Location directive, this will be set to the value of the Location directive. If LocationMatch, or wildcards or regular expressions are used with Location, the value will be the matched value in the URL and not the pattern.
Improvements¶
- (MODPYTHON-27) When using mod_python.publisher, the __auth__() and __access__() functions and the __auth_realm__ string can now be nested within a class method as a well a normal function.
- (MODPYTHON-90) The PythonEnablePdb configuration option will now be ignored if Apache hasn’t been started up in single process mode.
- (MODPYTHON-91) If running Apache in single process mode with PDB enabled and the “quit” command is used to exit that debug session, an exception indicating that the PDB session has been aborted is raised rather than None being returned with a subsequent error complaining about the handler returning an invalid value.
- (MODPYTHON-93) Improved util.FieldStorage efficiency and made the interface more dictionary like.
- (MODPYTHON-101) Force an exception when handler evaluates to something other than None but is otherwise not callable. Previously an exception would not be generated if the handler evaluated to False.
- (MODPYTHON-107) Neither mod_python.publisher nor mod_python.psp explicitly flush output after writing the content of the response back to the request object. By not flushing output it is now possible to use the “CONTENT_LENGTH” output filter to add a “Content-Length” header.
- (MODPYTHON-111) Note made in session documentation that a save is required to avoid session timeouts.
- (MODPYTHON-125) The req.handler attribute is now writable. This allows a handler executing in a phase prior to the response phase to specify which Apache module will be responsible for generating the content.
- (MODPYTHON-128) Made the req.canonical_filename attribute writable. Changed the req.finfo attribute from being a tuple to an actual object. For backwards compatibility the attributes of the object can still be accessed as if they were a tuple. New code however should access the attributes as member data. The req.finfo attribute is also now writable and can be assigned to using the result of calling the new function apache.stat(). This function is a wrapper for apr_stat().
- (MODPYTHON-129) When specifying multiple handlers for a phase, the status returned by each handler is now treated the same as how Apache would treat the status if the handler was registered using the low level C API. What this means is that whereas stacked handlers of any phase would in turn previously be executed as long as they returned apache.OK, this is no longer the case and what happens is dependent on the phase. Specifically, a handler returning apache.DECLINED no longer causes the execution of subsequent handlers for the phase to be skipped. Instead, it will move to the next of the stacked handlers. In the case of PythonTransHandler, PythonAuthenHandler, PythonAuthzHandler and PythonTypeHandler, as soon as apache.OK is returned, subsequent handlers for the phase will be skipped, as the result indicates that any processing pertinent to that phase has been completed. For other phases, stacked handlers will continue to be executed if apache.OK is returned as well as when apache.DECLINED is returned. This new interpretation of the status returned also applies to stacked content handlers listed against the PythonHandler directive even though Apache notionally only ever calls at most one content handler. Where all stacked content handlers in that phase run, the status returned from the last handler becomes the overall status from the content phase.
- (MODPYTHON-141) The req.proxyreq and req.uri attributes are now writable. This allows a handler to setup these values and trigger proxying of the current request to a remote server.
- (MODPYTHON-142) The req.no_cache and req.no_local_copy attributes are now writable.
- (MODPYTHON-143) Completely reimplemented the module importer. This is now used whenever modules are imported corresponding to any of the Python*Handler, Python*Filter and PythonImport directives. The module importer is still able to be used directly using the apache.import_module() function. The new module importer no longer supports automatic reloading of packages/modules that appear on the standard Python module search path as defined by the PythonPath directive or within an application by direct changes to sys.path. Automatic module reloading is however still performed on file based modules (not packages) which are located within the document tree where handlers are located. Locations within the document tree are however no longer added to the standard Python module search path automatically as they are maintained within a distinct importer search path. The PythonPath directive MUST not be used to point at directories within the document tree. To have additional directories be searched by the module importer, they should be listed in the mod_python.importer.path option using the PythonOption directive. This is a path similar to how PythonPath argument is supplied, but MUST not reference sys.path nor contain any directories also listed in the standard Python module search path. If an application does not appear to work under the module importer, the old module importer can be reenabled by setting the mod_python.legacy.importer option using the PythonOption directive to the value ‘*’. This option must be set in the global Apache configuration.
- (MODPYTHON-152) When in a sub request, when a request is the result of an internal redirect, or when when returning from such a request, the req.main, req.prev and req.next members now correctly return a reference to the original Python request object wrapper first created for the specific request_rec instance rather than creating a new distinct Python request object. This means that any data added explicitly to a request object can be passed between such requests.
- (MODPYTHON-178) When using mod_python.psp, if the PSP file which is the target of the request doesn’t actually exist, an apache.HTTP_NOT_FOUND server error is now returned to the client rather than raising a ValueError exception which results in a 500 internal server error. Note that if using SetHandler and the request is against the directory and no DirectoryIndex directive is specified which lists a valid PSP index file, then the same apache.HTTP_NOT_FOUND server error is returned to the client.
- (MODPYTHON-196) For completeness, added req.server.log_error() and req.connection.log_error(). The latter wraps ap_log_cerror() (when available), allowing client information to be logged along with message from a connection handler.
- (MODPYTHON-206) The attribute req.used_path_info is now modifiable and can be set from within handlers. This is equivalent to having used the AcceptPathInfo directive.
- (MODPYTHON-207) The attribute req.args is now modifiable and can be set from within handlers.
Bug Fixes¶
- (MODPYTHON-38) Fixed issue when using PSP pages in conjunction with publisher handler or where a PSP error page was being triggered, that form parameters coming from content of a POST request weren’t available or only available using a workaround. Specifically, the PSP page will now use any FieldStorage object instance cached as req.form left there by preceding code.
- (MODPYTHON-43) Nested __auth__() functions in mod_python.publisher now execute in context of globals from the file the function is in and not that of mod_python.publisher itself.
- (MODPYTHON-47) Fixed mod_python.publisher so it will not return a HTTP Bad Request response when mod_auth is being used to provide Digest authentication.
- (MODPYTHON-63) When handler directives are used within Directory or DirectoryMatch directives where wildcards or regular expressions are used, the handler directory will be set to the shortest directory matched by the directory pattern. Handler directives can now also be used within Files and FilesMatch directives and the handler directory will correctly resolve to the directory corresponding to the enclosing Directory or DirectoryMatch directive, or the directory the .htaccess file is contained in.
- (MODPYTHON-76) The FilterDispatch callback should not flush the filter if it has already been closed.
- (MODPYTHON-84) The original change to fix the symlink issue for req.sendfile() was causing problems on Win32, plus code needed to be changed to work with APR 1.2.7.
- (MODPYTHON-100) When using stacked handlers and a SERVER_RETURN exception was used to return an OK status for that handler, any following handlers weren’t being run if appropriate for the phase.
- (MODPYTHON-109) The Py_Finalize() function was being called on child process shutdown. This was being done though from within the context of a signal handler, which is generally unsafe and would cause the process to lock up. This function is no longer called on child process shutdown.
- (MODPYTHON-112) The req.phase attribute is no longer overwritten by an input or output filter. The filter.is_input member should be used to determine if a filter is an input or output filter.
- (MODPYTHON-113) The PythonImport directive now uses the apache.import_module() function to import modules to avoid reloading problems when same module is imported from a handler.
- (MODPYTHON-114) Fixed race conditions on setting sys.path when the PythonPath directive is being used as well as problems with infinite extension of path.
- (MODPYTHON-120) (MODPYTHON-121) Fixes to test suite so it will work on virtual hosting environments where localhost doesn’t resolve to 127.0.0.1 but the actual IP address of the host.
- (MODPYTHON-126) When Python*Handler or Python*Filter directive is used inside of a Files directive container, the handler/filter directory value will now correctly resolve to the directory corresponding to any parent Directory directive or the location of the .htaccess file the Files directive is contained in.
- (MODPYTHON-133) The table object returned by req.server.get_config() was not being populated correctly to be the state of directives set at global scope for the server.
- (MODPYTHON-134) Setting PythonDebug to Off, wasn’t overriding On setting in parent scope.
- (MODPYTHON-140) The util.redirect() function should be returning server status of apache.DONE and not apache.OK otherwise it will not give desired result if used in non content handler phase or where there are stacked content handlers.
- (MODPYTHON-147) Stopped directories being added to sys.path multiple times when PythonImport and PythonPath directive used.
- (MODPYTHON-148) Added missing Apache contants apache.PROXYREQ_RESPONSE and apache.HTTP_UPGRADE_REQUIRED. Also added new constants for Apache magic mime types and values for interpreting the req.connection.keepalive and req.read_body members.
- (MODPYTHON-150) In a multithread MPM, the apache.init() function could be called more than once for a specific interpreter instance whereas it should only be called once.
- (MODPYTHON-151) Debug error page returned to client when an exception in a handler occurred wasn’t escaping special HTML characters in the traceback or the details of the exception.
- (MODPYTHON-157) Wrong interpreter name used for fixup handler phase and earlier, when PythonInterpPerDirectory was enabled and request was against a directory but client didn’t provide the trailing slash.
- (MODPYTHON-159) Fix FieldStorage class so that it can handle multiline headers.
- (MODPYTHON-160) Using PythonInterpPerDirective when setting content handler to run dynamically with req.add_handler() would cause Apache to crash.
- (MODPYTHON-161) Directory argument supplied to req.add_handler() is canonicalized and a trailing slash added automatically. This is needed to ensure that the directory is always in POSIX path style as used by Apache and that convention where directories associated with directives always have trailing slash is adhered to. If this is not done, a different interpreter can be chosen to that expected when the PythonInterpPerDirective is used.
- (MODPYTHON-166) PythonHandlerModule was not setting up registration of the PythonFixupHandler or PythonAuthenHandler. For the latter this meant that using Require directive with PythonHandlerModule would cause a 500 error and complaint in error log about “No groups file”.
- (MODPYTHON-167) When PythonDebug was On and and exception occurred, the response to the client had a status of 200 when it really should have been a 500 error status indicating that an internal error occurred. A 500 error status was correctly being returned when PythonDebug was Off.
- (MODPYTHON-168) Fixed psp_parser error when CR is used as a line terminator in psp code. This may occur with some older editors such as GoLive on Mac OS X.
- (MODPYTHON-175) Fixed problem whereby a main PSP page and an error page triggered from that page both accessing the session object would cause a deadlock.
- (MODPYTHON-176) Fixed issue whereby PSP code would unlock session object which it had inherited from the caller meaning caller could no longer use it safely. PSP code will now only unlock session if it created it in the first place.
- (MODPYTHON-179) Fixed the behaviour of req.readlines() when a size hint was provided. Previously, it would always return a single line when a size hint was provided.
- (MODPYTHON-180) Publisher would wrongly output a warning about nothing to publish if req.write() or req.sendfile() used and data not flushed, and then published function returned None.
- (MODPYTHON-181) Fixed memory leak when mod_python handlers are defined for more than one phase at the same time.
- (MODPYTHON-182) Fixed memory leak in req.readline().
- (MODPYTHON-184) Fix memory leak in apache.make_table(). This was used by util.FieldStorage class so affected all code using forms.
- (MODPYTHON-185) Fixed segfault in psp.parsestring(src_string) when src_string is empty.
- (MODPYTHON-187) Table objects could crash in various ways when the value of an item was NULL. This could occur for SCRIPT_FILENAME when the req.subprocess_env table was accessed in the post read request handler phase.
- (MODPYTHON-189) Fixed representation returned by calling repr() on a table object.
- (MODPYTHON-191) Session class will no longer accept a normal cookie if a signed cookie was expected.
- (MODPYTHON-194) Fixed potential memory leak due to not clearing the state of thread state objects before deleting them.
- (MODPYTHON-195) Fix potential Win32 resource leaks in parent Apache process when process restarts occur.
- (MODPYTHON-198) Python 2.5 broke nested __auth__/__access__/__auth_realm__ in mod_python.publisher.
- (MODPYTHON-200) Fixed problem whereby signed and marshalled cookies could not be used at the same time. When expecting marshalled cookie, any signed, but not marshalled cookies will be returned as normal cookies.
Changes from version 3.2.8¶
New Features¶
- (MODPYTHON-78) Added support for Apache 2.2.
- (MODPYTHON-94) New req.is_https() and req.ssl_var_lookup() methods. These communicate direct with the Apache mod_ssl module, allowing it to be determined if the connection is using SSL/TLS and what the values of internal ssl variables are.
- (MODPYTHON-131) The directory used for mutex locks can now be specified at at compile time using ./configure –with-mutex-dir value or at run time with PythonOption mod_python.mutex_directory value.
- (MODPYTHON-137) New req.server.get_options() method. This returns the subset of Python options set at global scope within the Apache configuration. That is, outside of the context of any VirtualHost, Location, Directory or Files directives.
- (MODPYTHON-145) The number of mutex locks can now be specified at run time with PythonOption mod_python.mutex_locks value.
- (MODPYTHON-172) Fixed three memory leaks that were found in _apachemodule.parse_qsl, req.readlines and util.cfgtree_walk.
Improvements¶
- (MODPYTHON-77) Third party C modules that use the simplified API for the Global Interpreter Lock (GIL), as described in PEP 311, can now be used. The only requirement is that such modules can only be used in the context of the “main_interpreter”.
- (MODPYTHON-119) DbmSession unit test no longer uses the default directory for the dbm file, so the test will not interfer with the user’s current apache instance.
- (MODPYTHON-158) Added additional debugging and logging output for where mod_python cannot initialise itself properly due to Python or mod_python version mismatches or missing Python module code files.
Bug Fixes¶
- (MODPYTHON-84) Fixed request.sendfile() bug for symlinked files on Win32.
- (MODPYTHON-122) Fixed configure problem when using bash 3.1.x.
- (MODPYTHON-173) Fixed DbmSession to create db file with mode 0640.
Changes from version 3.2.7¶
Security Fix¶
- (MODPYTHON-135) Fixed possible directory traversal attack in FileSession. The session id is now checked to ensure it only contains valid characters. This check is performed for all sessions derived from the BaseSession class.
Changes from version 3.1.4¶
New Features¶
- New apache.register_cleanup() method.
- New apache.exists_config_define() method.
- New file-based session manager class.
- Session cookie name can be specified.
- The maximum number of mutexes mod_python uses for session locking can now be specifed at compile time using configure –with-max-locks.
- New a version attribute in mod_python module.
- New test handler testhandler.py has been added.
Improvements¶
- Autoreload of a module using apache.import_module() now works if modification time for the module is different from the file. Previously, the module was only reloaded if the the modification time of the file was more recent. This allows for a more graceful reload if a file with an older modification time needs to be restored from backup.
- Fixed the publisher traversal security issue
- Objects hierarchy a la CherryPy can now be published.
- mod_python.c now logs reason for a 500 error
- Calls to PyErr_Print in mod_python.c are now followed by fflush()
- Using an empty value with PythonOption will unset a PythonOption key.
- req.path_info is now a read/write member.
- Improvements to FieldStorage allow uploading of large files. Uploaded files are now streamed to disk, not to memory.
- Path to flex is now discovered at configuration time or can be specifed using configure –with-flex=/path/to/flex.
- sys.argv is now initialized to [“mod_python”] so that modules like numarray and pychart can work properly.
Bug Fixes¶
- Fixed memory leak which resulted from circular references starting from the request object.
- Fixed memory leak resulting from multiple PythonOption directives.
- Fixed Multiple/redundant interpreter creation problem.
- Cookie attributes with attribute names prefixed with $ are now ignored. See Section 4.7 for more information.
- Bug in setting up of config_dir from Handler directives fixed.
- mod_python.publisher will now support modules with the same name but in different directories
- Fixed continual reloading of modules problem
- Fixed big marshalled cookies error.
- Fixed mod_python.publisher extension handling
- mod_python.publisher default index file traversal
- mod_python.publisher loading wrong module and giving no warning/error
- apply_fs_data() now works with “new style” objects
- File descriptor fd closed after ap_send_fd() in req_sendfile()
- Bug in mem_cleanup in MemorySession fixed.
- Fixed bug in _apache._global_lock() which could cause a segfault if the lock index parameter is greater number of mutexes created at mod_python startup.
- Fixed bug where local_ip and local_host in connection object were returning remote_ip and remote_host instead
- Fixed install_dso Makefile rule so it only installs the dso, not the python files
- Potential deadlock in psp cache handling fixed
- Fixed bug where sessions are used outside <Directory> directive.
- Fixed compile problem on IRIX. ln -s requires both TARGET and LINK_NAME on IRIX. ie. ln -s TARGET LINK_NAME
- Fixed ./configure problem on SuSE Linux 9.2 (x86-64). Python libraries are in lib64/ for this platform.
- Fixed req.sendfile() problem where sendfile(filename) sends the incorrect number of bytes when filename is a symlink.
- Fixed problem where util.FieldStorage was not correctly checking the mime types of POSTed entities
- Fixed conn.local_addr and conn.remote_addr for a better IPv6 support.
- Fixed psp_parser.l to properly escape backslash-n, backslash-t and backslash-r character sequences.
- Fixed segfault bug when accessing some request object members (allowed_methods, allowed_xmethods, content_languages) and some server object members (names, wild_names).
- Fixed request.add_handler() segfault bug when adding a handler to an empty handler list.
- Fixed PythonAutoReload directive so that AutoReload can be turned off.
- Fixed connection object read() bug on FreeBSD.
- Fixed potential buffer corruption bug in connection object read().
Changes from version 2.x¶
- Mod_python はもはや Apache 1.3 では動作せず、Apache 2.x だけをサポートするようになりました。
- Python 2.2.1 よりも前のバージョンでは動作しなくなりました。
- Apache フィルタをサポートするようになりました。
- Apache 接続ハンドラをサポートするようになりました。
- リクエストオブジェクトがinternal_redirect() をサポートするようになりました。
- 接続オブジェクトに read(), readline() および write() が追加されました。
- サーバオブジェクトに get_config() が追加されました。
- httpdapi ハンドラが撤廃されました。
- Zpublisher ハンドラが撤廃されました。
- ユーザ名はreq.connection.user ではなくreq.user になりました。
歴史とライセンス¶
mod_python の歴史¶
mod_python は、もともと Httpdapy (1997) というプロジェクトに端を発しています。 長い間、 httddapy が mod_python と呼ばれることはありませんでしたが、これは httpdapy が Apache 固有のものを目指してはいなかったからです。 httpdapy はクロスプラットフォームになるよう設計されていて、実際、最初に書かれた httpdapy は Netscape サーバ向けでした (1997 年当時は Nsapy と呼ばれていました)。
Nsapy 自体は独自のコンセプトに基づいていて、 “Internet Programming with Python” by Aaron Watters, Guido Van Rossum and James C. Ahlstrom, ISBN 1-55851-484-8 の中で、 Aaron Watters によって書かれました。
Aaron の洞察なくしては、 mod_python は生まれなかったでしょう。httpdpy の README ファイルには、以下のように書かれています:
Nsapy は Netscape サーバでしか動作しないが、その設計はきわめて汎用的で、 Netscape サーバに限定されない優れたアイデアに根ざしている。
拡張性、簡潔さ、効率性の組み合わせによって出来ていて、 Python のもたらす恩恵をあますところなく使い、 Python の精神を体現している。
以下に引用した httpdapy の README ファイルは、当時の課題と、 HTTP サーバへに Python を埋め込んで解決した経緯をうまく説明しています:
数年前、初めて WWW アプリケーションを開発しているときに、(商用のリレーショナルデータベースであれ、それ以外であれ) RDB に接続する必要のあるプログラムを CGI で組むと、非常に低速になるということがわかりました。
というのも、検索を行うたびに数メガバイトものサイズのインタプリタがロードされるし、データベースライブラリ自体も大きくて、おまけに、データベースへの接続と認証のプロセス、 DNS の名前解決や暗号化、メモリ確保... といった処理が入るために、オーバヘッドが非常に大きくなるからです。
アプリケーションの高速化に迫られて、私は Python を使い続けるのをあきらめかけて、WWW とデータベースの統合に特化していると謳ったツールを探しはじめました。
MS の ASP は、全く信頼する気になれませんでしたし、Netscape の LiveWire の低速さとバグの多さにはイライラしました。
Cold Fusion は有望でしたが、html ライクなタグを書くのは、プログラムの可読性をアセンブラ並みにすると、すぐに気づきました。
PHP についても同じです。何よりも、私は Python で書きたいと *心の底から* 願っていたのです。
ちょうどそのころ、 Internet Programming With Python という本が出版され、Netscape サーバに Python を埋め込む方法を解説した章に惹かれました。
その例題を自分のプロジェクトに使ってみて、後にNsapy と呼ばれる、 Windows NT と Solaris の両方でコンパイルできる改良版を開発したのです。
Naspy はNetscape サーバでしか動きませんでしたが、Naspy はPython の精神に適った、とても洗練された汎用のオブジェクト指向設計だったため、他の Web サーバにかんたんに移植できました。
折しも、 Netscape 製のサーバは人気を失いつつありました。
そこで私は Nsapy を他のサーバに移植することにしました。
手始めに、もっとも人気のあった Apache に移植したのです。
かくして、Nsapy から httpdapy が誕生したのです。
... この話には続きがあります。 正直なところ、全てのサーバ向けにHttpdapy を書くのは、最初に考えていたよりもちょっと大きな仕事になるし、さして興味も沸かなかったのです。
それよりも、人気の高い、 Perl の Apache 拡張である mod_perl と同じような (あるいはそれ以上の) 機能をもたらすような Python の Apache 拡張を作るのはとてもワクワクするできごとに思えたのです。
こうして mod_python はできました。最初の mod_python をリリースしたのは 2000 年の 3 月でした。
ライセンス¶
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Apache License:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
このドキュメントについて¶
このドキュメントは reStructuredText ソースで書かれていて、 Python ドキュメントの作成ツール、 Sphinx でビルドできます。