1. 程式人生 > >python3 服務端使用CGI指令碼處理POST的Json資料

python3 服務端使用CGI指令碼處理POST的Json資料

傳送端程式碼

#!/usr/bin/env python3
#coding=utf-8
#agent.py
import requests
import json
import urllib.request

url='http://127.0.0.1:8000/cgi-bin/post.py' 
data={'openid':'fuyou','to_groupid':'yes'}  
data = json.dumps(data)  
data=bytes(data,'utf8')  
request=urllib.request.Request(url)
request.method='POST'
request.data = data
request.add_header('Content-Type','application/json')
with urllib.request.urlopen(request) as r:
	print()
	print(r.read().decode('utf-8'))

伺服器端(接收端)

#!/usr/bin/env python3
#coding=utf-8
#/cgi-bin/post.py
import os,sys,json
con = int(os.environ["CONTENT_LENGTH"])
req_body = sys.stdin.read(con)
my_dict = json.loads(req_body)
print('Content-Type: text/html; charset=utf-8\n')
print("Hello, World!")
print("vv:{0}".format(my_dict['openid']))
print("vv:{0}".format(my_dict))
print(my_dict)

在/cgi-bin 目錄的父目錄,執行

$ python3 -m http.server --cgi 8000

另開終端

$ python3 agent.py