python如何获取表单数据,在Python3 CGI脚本中,如何在POST中读取原始表单数据?

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

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))

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

returns

query=foo=bar&ggg=3&aaa=bbb&zzz=qqq

ggg=3

foo=bar << note that foo now comes after ggg

aaa=bbb

zzz=qqq

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

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?

Just read from stdin: (this is Python3 code, not sure if Python2 would be any different)

query_string = sys.stdin.read()

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)

which, much like cgi.FieldStorage, returns a multimap, hence the name multiform.

For some more details, I blogged about it here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值