使用AppEngine发送具有相同名称的多个POST数据项

时间:2022-04-03 16:51:32

I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values.

我尝试使用AppEngine中的urlfetch将POST数据发送到服务器。其中一些POST数据项具有相同的名称,但具有不同的值。

form_fields = {
   "data": "foo",
   "data": "bar"
}

form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url="http://www.foo.com/", payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'})

However, in this example, the server seems to receieve only one item named data, with the value bar. How could I solve this problem?

但是,在此示例中,服务器似乎只接收一个名为data的项,其值为bar。我怎么能解决这个问题?

2 个解决方案

#1


14  

Modify your form_fields dictionary so that fields with the same name are turned into lists, and use the doseq argument to urllib.urlencode:

修改form_fields字典,以便将具有相同名称的字段转换为列表,并将doseq参数用于urllib.urlencode:

form_fields = {
   "data": ["foo","bar"]
}

form_data = urllib.urlencode(form_fields, doseq=True)

At this point, form_data is 'data=foo&data=bar', which is what I think you need.

此时,form_data是'data = foo&data = bar',这是我认为你需要的。

#2


1  

A normal python dict can't handle this sort of thing; use something like a webob.MultiDict:

一个普通的python dict无法处理这类事情;使用类似webob.MultiDict的东西:

>>> z = webob.MultiDict([('foo', 'bar'), ('foo', 'baz')])
>>> urllib.urlencode(z)
'foo=bar&foo=baz'

#1


14  

Modify your form_fields dictionary so that fields with the same name are turned into lists, and use the doseq argument to urllib.urlencode:

修改form_fields字典,以便将具有相同名称的字段转换为列表,并将doseq参数用于urllib.urlencode:

form_fields = {
   "data": ["foo","bar"]
}

form_data = urllib.urlencode(form_fields, doseq=True)

At this point, form_data is 'data=foo&data=bar', which is what I think you need.

此时,form_data是'data = foo&data = bar',这是我认为你需要的。

#2


1  

A normal python dict can't handle this sort of thing; use something like a webob.MultiDict:

一个普通的python dict无法处理这类事情;使用类似webob.MultiDict的东西:

>>> z = webob.MultiDict([('foo', 'bar'), ('foo', 'baz')])
>>> urllib.urlencode(z)
'foo=bar&foo=baz'