4
5

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.

[python3] 簡易サーバでJSONデータ受け渡し [POST]

Last updated at Posted at 2019-02-02

やりたいこと

python3にて簡単なサーバを立ててJsonでデータを受け渡ししたいだけ。

では始めます。

ソース

server.py
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import http.server as s
import json

class MyHandler(s.BaseHTTPRequestHandler):
    def do_POST(self):

        # リクエスト取得
        content_len  = int(self.headers.get("content-length"))
        body = json.loads(self.rfile.read(content_len).decode('utf-8'))

        # レスポンス処理
        body["answer"] = "晴れです。"
        self.send_response(200)
        self.send_header('Content-type', 'application/json;charset=utf-8')
        self.end_headers()
        body_json = json.dumps(body, sort_keys=False, indent=4, ensure_ascii=False) 
        self.wfile.write(body_json.encode("utf-8"))

# サーバ起動
host = '0.0.0.0'
port = 3333
httpd = s.HTTPServer((host, port), MyHandler)
httpd.serve_forever()

実行

$ ./server.py 

クエリ発行

$ curl -XPOST 'http://localhost:3333/test' -d '{ "question": "今日の天気は" }'
{
    "question": "今日の天気は",
    "answer": "晴れです。"
}
4
5
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
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?