やりたいこと
pythonで簡易サーバを立ててcurlを投げ、内容を確認
[手順1] サーバ起動 (ソースは後述)
$ ./server_python3.py
サーバを起動しました。ポート:8000
[手順2] curl送信
$ curl -X GET 'http://localhost:8000/test?aaa=bbb&ccc=ddd' -d 'ああ'
method: GET
body : ああ
params: {'aaa': ['bbb'], 'ccc': ['ddd']}
サーバのソース
コピペで動くと思います
python3用
server_python3.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import http.server as s
from urllib.parse import urlparse
from urllib.parse import parse_qs
class MyHandler(s.BaseHTTPRequestHandler):
def do_POST(self):
self.make_data()
def do_GET(self):
self.make_data()
def make_data(self):
# urlパラメータを取得
parsed = urlparse(self.path)
# urlパラメータを解析
params = parse_qs(parsed.query)
# body部を取得
content_len = int(self.headers.get("content-length"))
req_body = self.rfile.read(content_len).decode("utf-8")
# 返信を組み立て
body = "method: " + str(self.command) + "\n"
body += "params: " + str(params) + "\n"
body += "body : " + req_body + "\n"
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.send_header('Content-length', len(body.encode()))
self.end_headers()
self.wfile.write(body.encode())
host = '0.0.0.0'
port = 8000
httpd = s.HTTPServer((host, port), MyHandler)
print('サーバを起動しました。ポート:%s' % port)
httpd.serve_forever()
python2用
server_python2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import SimpleHTTPServer as s
import BaseHTTPServer as b
from urlparse import urlparse
from urlparse import parse_qs
class MyHandler(s.SimpleHTTPRequestHandler):
def do_POST(self):
self.make_data()
def do_GET(self):
self.make_data()
def make_data(self):
# urlパラメータを取得
parsed = urlparse(self.path)
# urlパラメータを解析
params = parse_qs(parsed.query)
# body部を取得
content_len = int(self.headers.get("content-length", 0))
req_body = self.rfile.read(content_len).decode("utf-8")
# 返信を組み立て
body = "method: " + str(self.command) + "\n"
body += "params: " + str(params) + "\n"
body += "body : " + req_body + "\n"
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.send_header('Content-length', len(body.encode("utf-8")))
self.end_headers()
self.wfile.write(body.encode("utf-8"))
host = '0.0.0.0'
port = 8000
httpd = b.HTTPServer((host, port), MyHandler)
print('サーバを起動しました。ポート:%s' % port)
httpd.serve_forever()