0
0

More than 3 years have passed since last update.

Python3: JSON ファイルを http サーバーにアップロード

Last updated at Posted at 2019-11-27

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
0
0
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
0