gpt4 book ai didi

ajax - 如何在不使用 CGI 的情况下在 python3.x 中获取 POST "data"变量?

转载 作者:行者123 更新时间:2023-12-01 05:02:14 24 4
gpt4 key购买 nike

当我尝试调用 cgi.FieldStorage()python3.x cgi 脚本,我收到以下错误:

[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

我如何获得我的 POST data来自ajax调用的变量?

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");
}
});
}

最佳答案

根据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."

这个问题的解决方法是使用 sys.stdin.read读取 POST 数据参数。但是请注意,您的 cgi 应用程序 可以挂如果它希望读取某些内容并且没有发送任何内容。这可以通过读取 HTTP header 中的字节数来解决:
#!/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])

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

关于ajax - 如何在不使用 CGI 的情况下在 python3.x 中获取 POST "data"变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24638432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com