LoginSignup
4
7

More than 3 years have passed since last update.

Python で WSGI (Web Server Gateway Interface) に従ったシンプルな Web サーバで Hello World

Posted at

概要

  • Python で WSGI (Web Server Gateway Interface) に従ったシンプルな Web サーバを起動する
  • Python 標準ライブラリの wsgiref を使用する
  • 検証環境: Python 3.8.5 + macOS Catalina

WSGI と wsgiref について

Web Server Gateway Interface - Wikipedia

Web Server Gateway Interface (WSGI; ウィスキー) は、プログラミング言語Pythonにおいて、WebサーバとWebアプリケーション(もしくはWebアプリケーションフレームワーク)を接続するための、標準化されたインタフェース定義である。また、WSGIから着想を得て、他の言語でも同様のインタフェースが作られた。

wsgiref --- WSGI ユーティリティとリファレンス実装 — Python 3.8.5 ドキュメント

wsgiref は WSGI 仕様のリファレンス実装で、これは Web サーバやフレームワークに WSGI サポートを加えるのに利用できます。これは WSGI 環境変数やレスポンスヘッダを操作するユーティリティ、 WSGI サーバ実装時のベースクラス、WSGI アプリケーションを提供する デモ用 HTTP サーバ、それと WSGI サーバとアプリケーションの WSGI 仕様 (PEP 3333) 準拠のバリデーションツールを提供します。

ソースコード

以下の内容を app.py というファイル名で保存する。

# Hello World な WSGI アプリケーションを書く
def application(environ, start_response):
  status = '200 OK'
  headers = [('Content-type', 'text/plain; charset=utf-8')]
  body = 'hello, world'.encode('utf-8')
  start_response(status, headers)
  return [body]

# WSGI 仕様のリファレンス実装である wsgiref を利用する
from wsgiref import simple_server

if __name__ == '__main__':

  # WSGI HTTP サーバを起動
  host = ''
  port = 8000
  app = application # WSGI アプリケーションを指定
  server = simple_server.make_server(host, port, app)
  server.serve_forever()

WSGI HTTP サーバを起動

$ python app.py

WGGI HTTP サーバにアクセス

$ curl --include http://localhost:8000/
HTTP/1.0 200 OK
Date: Sat, 29 Aug 2020 04:33:33 GMT
Server: WSGIServer/0.2 CPython/3.8.5
Content-type: text/plain; charset=utf-8
Content-Length: 12

hello, world

参考資料

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7