如何在不使用 CGI 的情况下在 python3.x 中获取 POST“数据”变量?

Nuc*_*eon 4 ajax post encoding cgi python-3.x

当我尝试调用cgi.FieldStorage()一个python3.xCGI脚本,我得到以下错误:

[Traceback: error in module x on line y]:
    cgi.FieldStorage()
File "/usr/lib64/python3.3/cgi.py", line 553, in __init__
    self.read_single()
File "/usr/lib64/python3.3/cgi.py", line 709, in read_single
    self.read_binary()
File "/usr/lib64/python3.3/cgi.py", line 731, in read_binary
    self.file.write(data)
TypeError: must be str, not bytes
Run Code Online (Sandbox Code Playgroud)

如何data从 ajax 调用中获取我的 POST变量?

示例ajax调用:

function (param) {
    $.ajax({
       type: "POST",
       url: "/cgi-bin/mycgi.py/TestMethod",
       data: JSON.stringify({"foo": "bar"}),
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (result) {
           alert("Success " + result);
       },
       error: function () {
           alert("Failed");
       }
    });
}
Run Code Online (Sandbox Code Playgroud)

Nuc*_*eon 5

根据http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/

"There are also some special cases in the stdlib where strings are 
very confusing. The cgi.FieldStorage module which WSGI applications are 
sometimes still using for form data parsing is now treating QUERY_STRING 
as surrogate escaping, but instead of using utf-8 as charset for the URLs 
(as browsers) it treats it as the encoding returned by 
locale.getpreferredencoding(). I have no idea why it would do that, but 
it's incorrect. As workaround I recommend not using cgi.FieldStorage for 
query string parsing."
Run Code Online (Sandbox Code Playgroud)


解决这个问题的办法是使用sys.stdin.read读入POST数据参数。但是请注意,如果您的 cgi 应用程序希望读取某些内容而没有发送任何内容,则它可能会挂起。这是通过读取在 HTTP 标头中找到的字节数来解决的:

#!/usr/bin/env python3
import os, sys, json
data = sys.stdin.read(int(os.environ.get('HTTP_CONTENT_LENGTH', 0)))
# To get data in a native python dictionary, use json.loads
if data:
    print(list(json.loads(data).keys())) # Prints out keys of json

# (You need to wrap the .keys() in list() because it would otherwise return 
#  "dict_keys([a, b, c])" instead of [a, b, c])
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关 CGI 内部结构的更多信息:http : //oreilly.com/openbook/cgi/ch04_02.html