WSGIとDjangoのメモ

wsgiref.handlers.CGIHandlerっぽいものを自分で書いてDjangoのIt worked!を表示してみるメモ。

tests.py

# coding:utf-8
from django.conf.urls.defaults import *
urlpatterns = patterns('')

def start_response(status, response_headers, exc_info=None):
    """
    レスポンス開始のコールバック
    """
    print status
    print '--start headers--'
    print response_headers
    print '--end headers--'

def main():
    import os
    import sys
    from django.conf import settings, global_settings
    # Djangoを動かすにはsettings必須
    settings.configure(
        global_settings,
        ROOT_URLCONF='tests',
        SETTINGS_MODULE='foo.tests',
        DEBUG=True,
    )
    from django.core.handlers.wsgi import WSGIHandler

    # WSGIのenviron辞書を作る
    environ = os.environ.copy()
    environ['REQUEST_METHOD'] = 'GET'
    environ['SERVER_NAME'] = 'localhost'
    environ['SERVER_PORT'] = '80'

    # DjangoのWSGIハンドラインスタンス(WSGIアプリケーション)を作る
    application = WSGIHandler()
    # CGIHandler().run(application) のようなものを実装

    # WSGIアプリケーションを実行してレスポンスを取得
    response = application(environ, start_response)
    print '--start body--'
    # responseを出力
    for chunk in response:
        sys.stdout.write(chunk)
    print '\n--end body--'

if __name__ == '__main__':
    main()

普通はenvironもっと必要です。

実行結果

Q:\>python tests.py
200 OK
--start headers--
[('Content-Type', 'text/html')]
--end headers--
--start body--

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en"><head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django</title>
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; }
    h2 { margin-bottom:.8em; }
    h2 span { font-size:80%; color:#666; font-weight:normal; }
    h3 { margin:1em 0 .5em 0; }
    h4 { margin:0 0 .5em 0; font-weight: normal; }
    table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
    tbody td, tbody th { vertical-align:top; padding:2px 3px; }
    thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }
    tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
    ul { margin-left: 2em; margin-top: 1em; }
    #summary { background: #e0ebff; }
    #summary h2 { font-weight: normal; color: #666; }
    #explanation { background:#eee; }
    #instructions { background:#f6f6f6; }
    #summary table { border:none; background:transparent; }
  </style>
</head>

<body>
<div id="summary">
  <h1>It worked!</h1>
  <h2>Congratulations on your first Django-powered page.</h2>
</div>

<div id="instructions">
  <p>Of course, you haven't actually done any work yet. Here's what to do next:</p>
  <ul>
    <li>If you plan to use a database, edit the <code>DATABASE_*</code> settings in <code>foo/settings.py</code>.</li>
    <li>Start your first app by running <code>python foo/manage.py startapp [appname]</code>.</li>
  </ul>
</div>

<div id="explanation">
  <p>
    You're seeing this message because you have <code>DEBUG = True</code> in your
    Django settings file and you haven't configured any URLs. Get to work!
  </p>
</div>
</body></html>

--end body--