LoginSignup
24
27

More than 5 years have passed since last update.

Pythonで簡単にHTTPサーバを作る

Posted at

ちょっとした動作確認にさくっとHTTPサーバを作る場合の方法です.

CallbackServer.py
#!/usr/bin/env python

import requests
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse

def start(port, callback):
    def handler(*args):
        CallbackServer(callback, *args)
    server = HTTPServer(('', int(port)), handler)
    server.serve_forever()

class CallbackServer(BaseHTTPRequestHandler):
    def __init__(self, callback, *args):
        self.callback = callback
        BaseHTTPRequestHandler.__init__(self, *args)

    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        query = parsed_path.query
        self.send_response(200)
        self.end_headers()
        result = self.callback(query)
        message = '\r\n'.join(result)
        self.wfile.write(message)
        return

HTTPServerをベースにしてコールバック関数を設定しているクラスを定義しています.requestsはpip等でインストールしてください.

使い方はこんな感じ.

simple_test.py
#!/usr/bin/env python
# coding:utf-8

import sys
import CallbackServer

def callback_method(query):
    return ['Hello', 'World!', 'with', query]

if __name__ == '__main__':
    port = sys.argv[1]
    CallbackServer.start(port, callback_method)

ポート番号だけ受け取って,ポート番号とHTTPアクセスがあった場合に呼び出されるメソッド(callback_method)を渡せば後は勝手にHTTPサーバが上がってくれます.
callback_methodは引数にGETクエリ(URLの?より後ろ側)を受け取って,Responseとして返す文字列をreturnで返します.
文字列のリストを返せば勝手にCRLFで改行されます.

起動は

./simple_test.py 12345

という感じで実行して,後はブラウザからhttp://localhost:12345/?hoge=123とかにアクセスすると

Hello
World!
with
hoge=123

が出力されます.

24
27
1

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
24
27