【问题标题】:urllib2 Posting ZIP file errorurllib2 发布 ZIP 文件错误
【发布时间】:2013-12-10 23:22:06
【问题描述】:

我想在没有 pycurl 或其他库的情况下将我的应用程序/zip 数据发送到服务器。我是 cURL 的新手。首先,我使用此代码成功发送了 text/xml 数据

import urllib2
req = urllib2.Request("http://192.168.79.131/rest", headers = {"Content-type" : "text/xml" , "Accept" : "*/*"} , data = '<income><name>acme7</name></income>')
f = urllib2.urlopen(req)

但现在我想将我的 ZIP 文件上传到服务器。我试过这段代码:

import urllib2
zipPath = "c:/somedir/ways.zip"
zipData  = open(zipPath, "rb")
req = urllib2.Request("http://192.168.79.131/rest", headers = {"Content-type" : "application/zip" , "Accept" : "*/*"} , data = zipData)
f = urllib2.urlopen(req)

我收到了这些错误:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    f = urllib2.urlopen(req)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 386, in open
    protocol = req.get_type()
  File "C:\Python27\lib\urllib2.py", line 248, in get_type
    **raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: /rest/income**

【问题讨论】:

    标签: python curl urllib2


    【解决方案1】:

    您是否考虑过使用 Requests 之类的东西?它处理了很多 urllib2 的东西,所以你不必:

    import requests
    
    url = 'http://httpbin.org/post'
    files = {'file': open('c:/somedir/ways.zip', 'rb')}
    r = requests.post(url, files=files)
    print r
    

    打印:

    >>> <Response [200]>
    

    【讨论】:

    • 是因为你不能在哪里运行它吗?或者你认为安装 lib 不值得?
    • 我更喜欢 urllib2 因为也许用户不想安装其他库(完全是新手)
    • 包含外部库是一种常见的做法(尤其是在开源社区中)。由于请求的稳定性,您实际上是在帮您的用户一个忙。只需一条线即可安装并使其正常工作,并大大减少您的工作量。如果您过于担心它,请在代码中包含一个版本作为依赖项(使用适当的许可证)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多