在Python3 CGI脚本中,如何在POST中读取原始表单数据? [英] In a Python3 CGI script, how can I read the raw form data in a POST?
问题描述
是的,我知道cgi.FieldStorage
,但是作为某种形式的无序词典,它不保留原始数据的顺序(请参见下面的证明).由于我希望将此数据与PayPal IPN一起使用,因此 PayPal文档很重要,上面写着:"...您必须按照收到内容的确切顺序将其寄回..."
Yes, I'm aware of cgi.FieldStorage
, but, being some form of unordered dictionary, it does not preserve the order of the original data (see below for proof). Since I wish to use this data with PayPal IPN, order is important PayPal docs here, which say "...you must send back the contents in the exact order they were received..."
或者,os.environ.get('QUERY_STRING')
看起来很完美,但是,它似乎仅适用于GET .示例代码:(myscript.py)
Alternatively, os.environ.get('QUERY_STRING')
looks perfect, however, it seems to only work for a GET. Example code: (myscript.py)
#!/usr/bin/python3
import cgi, os
query = os.environ.get('QUERY_STRING') or 'no query'
print ("Content-type: text/plain\n\n")
print("query=" + query)
form = cgi.FieldStorage()
for key in form.keys():
print("\n" + key + '=' + form.getvalue(key))
使用浏览器中的GET,例如(请注意,foo是 before ggg)
Works with a GET from the browser, e.g. (note that foo is before ggg)
http://example.com/myscript.py/foo=bar&ggg=3&aaa=bbb&zzz=qqq
返回
query=foo=bar&ggg=3&aaa=bbb&zzz=qqq
ggg=3
foo=bar << note that foo now comes after ggg
aaa=bbb
zzz=qqq
但是,如果我使用Postman进行发布
However, if I use Postman to POST
POST /myscript.py HTTP/1.1
Host: example.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
foo=bar&ggg=3&aaa=bbb&zzz=qqq
它不返回查询字符串,并且,按预期,FormData没有保留顺序.
It returns no query string, and, as expected, the FormData did not preserve the order.
query=no query
ggg=3
foo=bar << note that foo now comes after ggg
aaa=bbb
zzz=qqq
推荐答案
不确定为什么没有人回答.经过一番摸索,我发现该解决方案非常简单.这就是为什么没人愿意回答吗?
Not sure why nobody answered. After a little futzing I discovered that the solution is incredibly simple. Is that why nobody bothered to answer?
只需从stdin中读取:(这是Python3代码,不确定Python2是否会有所不同)
Just read from stdin: (this is Python3 code, not sure if Python2 would be any different)
query_string = sys.stdin.read()
有一个缺点:这与cgi.FieldStorage()
不兼容,因为这也会尝试从stdin中读取.因此,如果您还希望一个好的字典来查找查询词,则有一个更简单的步骤:
There's one drawback: this is incompatible with cgi.FieldStorage()
, since that will also try to read from stdin. So, if you also want a nice dictionary to look up query terms, there is one more simple step:
multiform = urllib.parse.parse_qs(query_string)
(类似于cgi.FieldStorage)返回 multimap ,因此名称为multiform.
which, much like cgi.FieldStorage, returns a multimap, hence the name multiform.
有关更多详细信息,我在此处通过博客发了言.
这篇关于在Python3 CGI脚本中,如何在POST中读取原始表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!