0
1

More than 3 years have passed since last update.

Python3: JSON 形式の Post を処理する方法

Posted at

サーバープログラム (CGI)

sum_up_json.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#       sum_up_json.py
#
#                                               Jul/24/2021
#
# ---------------------------------------------------------------------
import  os
import  sys
import  json
import  cgi
#
# ---------------------------------------------------------------------
if os.environ['REQUEST_METHOD'] == 'POST':
    length, _ = cgi.parse_header(os.environ['CONTENT_LENGTH'])
    data = sys.stdin.buffer.read(int(length))
#
    json_str = data.decode("utf-8")
    data_aa = json.loads(json_str)
    aa = int(data_aa["aa"])
    bb = int(data_aa["bb"])
    data_aa['wa'] = aa + bb 
    data_aa['sa'] = aa - bb
    str_aa = json.dumps(data_aa)
#
    print('Content-Type: text/json; charset=utf-8')
    print("Access-Control-Allow-Origin: *\r\n")
    print(str_aa)
#   print(data.decode("utf-8"))
# ---------------------------------------------------------------------

テストスクリプト

go_post_json.sh
#
URL="http://localhost/python/sum_up/sum_up_json.py"
#
#
curl -X POST -H "Content-Type: application/json"  $URL \
    -d '{"aa":81, "bb":34 }'
0
1
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
0
1