猫型エンジニアのブログ

プログラム/ネットワーク系の技術関連をまとめたページです 

WSGIのお勉強 その2

WSGIに準拠したWebアプリケーション例

このページを参考にしました。

#wsgi-test1.py
def application(environ, start_response):
        start_response('200 OK', [('Content-type', 'text/plain')])
        return 'Hello, world'

from wsgiref import simple_server

if __name__ == '__main__':
        server = simple_server.make_server('', 8080, application)
        server.serve_forever()                            

 simpe_server.make_server関数で、8080番にリクエストが来た際はWSGIアプリケーションとしてのApplicationが呼び出されて、レスポンスがなされます。

実行例

ターミナル上で上のコードを実行した状態で、別ターミナルから8080番にcurlコマンドでリクエストを投げます。

$ python wsgi-test1.py 
127.0.0.1 - - [02/Apr/2014 21:31:35] "GET / HTTP/1.1" 200 12
127.0.0.1 - - [02/Apr/2014 21:31:35] "GET /favicon.ico HTTP/1.1" 200 12
127.0.0.1 - - [02/Apr/2014 21:31:35] "GET /favicon.ico HTTP/1.1" 200 12
$ curl -v http://localhost:8080
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Sat, 05 Apr 2014 12:31:24 GMT
< Server: WSGIServer/0.1 Python/2.7.5
< Content-type: text/plain
Hello, world

確かにサーバとして動作していることを確認できました。