我试图简单地读取传递给 python cgi 脚本的 json 数据,但是当我调用 sys.stdin 时它挂起。我用 --honour-stdin 启动了 uWSGI,它没有任何区别。我正在使用 nginx -> uWSGI 和 cgi 插件。
data = json.load(sys.stdin)
print "Status: 200 OK"
print "Content-Type: application/json"
print "Length:", len(data)
print ""
print data
编辑:如果我限制它读取的字符数,它就不会挂起。所以它正在等待 EOF。是否缺少某些 uWSGI 设置?
请您参考如下方法:
您可以使用 os.environ['CONTENT_LENGTH'] 环境变量来读取确切的字节数,作为标准输入未被 CGI 库终止的解决方法。
import os
if not os.environ['CONTENT_LENGTH']:
data = {}
else:
post_length = int(os.environ['CONTENT_LENGTH'])
# post_length stores byte count, but stdin.read, apparently, takes the character count
post_string = sys.stdin.buffer.read(post_length).decode('utf-8')
data = json.loads(post_string)
假设您的文本使用 utf-8 编码。
