Published On: 2014-11-20|Last Updated: 2014-11-20|Categories: Python|Tags: , |

Python 3.4 をビルドしてインストールする

ssh で接続して次のように作業します。

[code language=”shell”] cd $HOME
wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz –no-check-certificate -O -| tar xz
pushd Python-3.4.2/
./configure –prefix $HOME && make && make test && make install
popd
$HOME/bin/python3 -c "print(‘hello, python’)"[/code]

この状態だと次のように警告が出て使用できないモジュールが報告されますが、無視しても問題ないでしょう。

The necessary bits to build these optional modules were not found:

_lzma _tkinter readline

ここまで来ると普通に pip や venv が使えますので適当にセットアップします。

Apache で動くように設定する。

XREA ではリバースプロキシ用にサーバーを立てたりできませんし、mod_wsgi も使用できません。スクリプトは CGI 経由で使用するしかありません。

/virtual/YOU/public_html 以下の適当なディレクトリに次のような .htaccess ファイルを作成します。

この例では RewriteRule で Authorization ヘッダーを Apache が処理しないようにしています。

このディレクトリにリクエストを発行すると index.py が呼び出されます。クライアント側の URL のパスの最後のスラッシュ (‘/’) は必須なので注意してください。

[code language=”text”] AddHandler cgi-script .py
# AddHandler cgi-script-debug .py

DirectoryIndex index.py

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule ^.*$ index.py
[/code]

CGI から WSGI application を呼ぶ

今どきわざわざ Python 3.4 を使って CGI もないので簡単なラッパーを作成しました。

もし使用するときは shebang のパスを書き換えてください。

[code language=”python”] #!/virtual/YOU/bin/python3
# –– coding: utf-8 –
import sys
import os
import io
import collections
import wsgiref.util

def wrap_wsgi(app, *, environ: dict=os.environ, output: io.BufferedIOBase=sys.stdout.buffer,
              encoding='utf-8'):
    """Run WSGI application in CGI environment.
    """
    assert callable(app)
    assert isinstance(environ, collections.Mapping)
    assert isinstance(output, io.BufferedWriter)

    environ = environ.copy()
    environ.setdefault('PATH_INFO','/')
    if 'REMOTE_ADDR' in environ:
        environ.setdefault('REMOTE_HOST', environ['REMOTE_ADDR'])
    environ.setdefault('wsgi.input', sys.stdin.buffer)
    environ.setdefault('wsgi.errors', sys.stderr)
    wsgiref.util.setup_testing_defaults(environ)

    response_started = False
    write = output.write

    def start_response(status: str, headers: [(str, str)]):
        nonlocal response_started

        assert not response_started
        response_started = True

        assert isinstance(status, str)
        write(b'Status: ' + status.encode(encoding) + b'rn')

        for k, v in headers:
            assert isinstance(k, str)
            assert isinstance(v, str)
            write(k.encode(encoding) + b': ' + v.encode(encoding) + b'rn')

        write(b'rn')

    for chunk in app(environ, start_response):
        assert response_started
        assert isinstance(chunk, bytes)
        write(chunk)


if __name__ == '__main__':
    from wsgiref.simple_server import demo_app
    wrap_wsgi(demo_app)
[/code]

psycopg2 をインストールする

使用している XREA にインストールされている PostgreSQL 7.4.14 では psycopg2-2.5.4 がビルドできません。PostgreSQL 9 をインストールしてビルドします。

接続テストには http://www.sXXX.xrea.com/jp/admin.cgi のデータベースで設定した情報を使用します。文字コードは UNICODE にした方が良いでしょう。

[code language=”shell”] wget https://ftp.postgresql.org/pub/source/v9.3.5/postgresql-9.3.5.tar.gz –no-check-certificate -O – | tar xz
pushd postgresql-9.3.5/
./configure –prefix $HOME –without-readline && make && make install
popd

wget http://initd.org/psycopg/tarballs/psycopg2-latest.tar.gz -O - | tar xz
pushd psycopg2-2.5.4/
LD_LIBRARY_PATH=$HOME/lib $HOME/bin/python3 setup.py build_ext --pg-config $HOME/bin/pg_config --static-libpq build install
popd

$HOME/bin/python3 -c "import psycopg2; psycopg2.connect('dbname=? user=? password=?')"
[/code]

関連