代码之家  ›  专栏  ›  技术社区  ›  Anurag Uniyal

多部分表单发布到Google应用程序引擎不工作

  •  0
  • Anurag Uniyal  · 技术社区  · 15 年前

    我正在尝试使用httplib发布一个由多部分组成的表单,url托管在google app引擎上,在post上它说方法是不允许的,尽管使用urlib2的发布是有效的。附完整的工作实例。

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

    1. 我的mulipart表单邮政编码有问题吗?

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

    所以现在的问题仍然是,两种方法之间的区别是什么,可以先让它们发挥作用吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   Community CDub    7 年前

    Nick Johnson's 回答

    您是否尝试使用.request()而不是.putRequest()等通过httplib发送请求,并将头作为dict提供?

    它起作用了!

    推荐文章