最近有个项目要通过webserver的方式接收客户端通过POST传过来的url参数和json数据,看了web.py的例子,好像很容易的样子。
先说下环境Win10 pro版,python 3.7.4,web.py 0.4.0-dev1;测试代码如下:
import web
import json
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def POST(self, name):
data1 = web.data()
print('post data1: ', data1)
json_data = json.loads(data1)
print(json_data['age'])
i = web.input() #这行会报write的错
print('get: ', i)
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
print("hello world")
代码根据例子改的,Browser端的post发送如下:主要发送的ContentType: application/json
测试后报错,如下:
跟踪到cgi.py文件中,发现问题出在self.file.write(data)这行。
类型不对,改成 self.file.write(str(data,encoding=self.encoding)) 就可以了。
(这么改肯定是有风险了,不过,考虑到cgi原生态就不支持ContentType: application/json,也没别的办法了)