11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[pythonメモ] pythonでテストサーバー起動

Posted at

Qiita投稿練習も兼ねて、pythonコードのメモ投稿

pythonでテストサーバー起動

# -*- coding: utf-8 -*-

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
import json


class GetHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        print(parsed_path)

        # 成功レスポンス(200)を返す
        if parsed_path.path == "/ok-api":
            self.send_response(200)
            self.end_headers()
            self.wfile.write("OK")
            return

        # 失敗レスポンス(403)を返す
        elif parsed_path.path == "/ng-api":
            self.send_error(403, "NG!")
            self.end_headers()
            return

        # クエリパラメータ("left-str", "right-str")を連結した文字列を返す
        # /concat-str?left-str=Hello&right-str=World
        elif parsed_path.path == "/concat-str":
            # クエリパラメータのパース(dictionary型)
            querys = urlparse.parse_qs(parsed_path.query)
            if ("left-str" in querys) and ("right-str" in querys):
                concat_str = querys["left-str"][0] + querys["right-str"][0]
                self.send_response(200)
                self.end_headers()
                self.wfile.write(concat_str)
                
            else:
                #"left-str"と"right-str"のクエリがなかったらエラー
                self.send_error(400, "query NG!")
                self.end_headers()
                return

        # Jsonを返す
        elif parsed_path.path == "/return-json":
            data = [{u"name":u"尾崎豊", u"age":26},
                    {u"name":u"hide", u"age":33}]
            jsonData = json.dumps(data, ensure_ascii=False, encoding='utf-8')

            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()

            self.wfile.write(jsonData.encode("utf-8"))
            return

        else:
            self.send_error(400, "NG!")
            self.end_headers()
            return


    # Bodyを設定して送ると、こちらが呼ばれる
    def do_POST(self):
        
        # request取得
        content_len = int(self.headers.get("content-length"))
        request_body = self.rfile.read(content_len).decode("utf-8")

        try:
            # requestのjson読み込み
            data = json.loads(request_body)

            # 読み込んだ内容出力
            for key in data:
                print("key:{0} value:{1}".format(key, data[key]))

            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()

            # requestと同じjsonを返す
            self.wfile.write(request_body.encode("utf-8"))
            return
        
        except:
            self.send_error(400, "request NG!")
            self.end_headers()
            return

            
if __name__ == "__main__":
    host = "localhost"
    port = 8000

    server = HTTPServer((host, port), GetHandler)
    server.serve_forever()

実行後、"http://localhost:8000" にサーバーが立つ

アクセスパスに応じて処理実施
http://localhost:8000/ok-api
とか
http://localhost:8000/concat-str?left-str=Hello&right-str=World
でアクセスする

11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?