【问题标题】:Multipart form post to google app engine not working谷歌应用引擎的多部分表单发布不起作用
【发布时间】:2009-08-10 10:59:02
【问题描述】:

我正在尝试使用 httplib 发布多部分表单,url 托管在 google app 引擎上,在帖子上说不允许使用方法,尽管使用 urllib2 的帖子有效。附上完整的工作示例。

我的问题是两者之间有什么区别,为什么一个有效而另一个无效

  1. 我的多部分表单邮政编码有问题吗?

  2. 还是谷歌应用引擎有问题?

  3. 还是别的什么?


import httplib
import urllib2, urllib

# multipart form post using httplib fails, saying
# 405, 'Method Not Allowed'
url = "http://mockpublish.appspot.com/publish/api/revision_screen_create"
_, host, selector, _, _ = urllib2.urlparse.urlsplit(url)
print host, selector
h = httplib.HTTP(host)

h.putrequest('POST', selector)

BOUNDARY = '----------THE_FORM_BOUNDARY'
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
h.putheader('content-type', content_type)
h.putheader('User-Agent', 'Python-urllib/2.5,gzip(gfe)')
content = ""
L = []
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="test"')
L.append('')
L.append("xxx")
L.append('--' + BOUNDARY + '--')
L.append('')
content = '\r\n'.join(L)
h.putheader('content-length', str(len(content)))
h.endheaders()
h.send(content)

print h.getreply()

# post using urllib2 works
data = urllib.urlencode({'test':'xxx'})
request = urllib2.Request(url)
f = urllib2.urlopen(request, data)
output = f.read()
print output

编辑:将 putrequest 更改为 request 后(根据 Nick Johnson 的建议),它可以工作

url = "http://mockpublish.appspot.com/publish/api/revision_screen_create"
_, host, selector, _, _ = urllib2.urlparse.urlsplit(url)

h = httplib.HTTPConnection(host)

BOUNDARY = '----------THE_FORM_BOUNDARY'
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY

content = ""
L = []
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="test"')
L.append('')
L.append("xxx")
L.append('--' + BOUNDARY + '--')
L.append('')
content = '\r\n'.join(L)
h.request('POST', selector, content,{'content-type':content_type})
res = h.getresponse()
print res.status, res.reason, res.read()

所以现在的问题仍然是两种方法之间的区别是什么,并且可以首先使其起作用?

【问题讨论】:

  • 您是否尝试过使用 httplib 发送请求,使用 .request() 而不是 .putrequest() 等,将标头作为 dict 提供?
  • 实际上我想使用多部分表单数据发送文件,我可以使用请求吗?

标签: python google-app-engine forms html-post


【解决方案1】:

Nick Johnson's回答

您是否尝试过使用 httplib 发送请求,使用 .request() 而不是 .putrequest() 等,将标头作为字典提供?

有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2014-07-22
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多