Python の cgi で JSON ファイルをアップロードする方法です。
この例では、アップロードしたファイルが、
/var/tmp/json/example.json
に書き込まれます。
サーバーサイドの処理
json_receive.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# json_receive.py
#
# Nov/23/2019
#
# --------------------------------------------------------
import sys
import os
import string
import json
import fcntl
import cgi
import cgitb
cgitb.enable()
#
# --------------------------------------------------------
def file_write_proc(file_name,str_out):
#
fp_out = open(file_name,mode='w',encoding='utf-8')
fcntl.lockf(fp_out, fcntl.LOCK_EX)
fp_out.write(str_out)
fp_out.close()
#
# --------------------------------------------------------
def get_string_proc(ff,key):
if key in ff:
value = ff.getfirst(key,"")
else:
value = "0000"
#
return value
# --------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
ff=cgi.FieldStorage()
#
json_str = get_string_proc(ff,"json")
#
file_name = "/var/tmp/json/example.json"
file_write_proc(file_name,json_str)
#
print ("Content-type: text/json; charset=UTF-8\n\n")
print (json_str)
sys.stderr.write("*** 終了 ***\n")
#
# --------------------------------------------------------
クライアントの処理
json_send.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# json_send.py
#
# Nov/27/2019
#
# ------------------------------------------------------------------
import sys
import json
import requests
from file_io import file_to_str_proc
# ------------------------------------------------------------------
def file_to_str_proc(file_in):
str_out = ""
try:
fp_in = open(file_in,encoding='utf-8')
str_out = fp_in.read()
fp_in.close()
except Exception as ee:
sys.stderr.write("*** error *** file_to_str_proc ***\n")
sys.stderr.write(str (ee))
#
return str_out
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
file_json = sys.argv[1]
#
json_str = file_to_str_proc(file_json)
#
url="https://example.com/json_receive/json_receive.py"
args={}
args['json'] = json_str
#
rr=requests.post(url,args)
print(rr.text)
#
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------
クライアントの使い方
./json_send.py in01.json