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 

 

你可能感兴趣的:(201809实习,python)