【问题标题】:Downloading file with Python results in only 4.1kB使用 Python 下载文件仅 4.1kB
【发布时间】:2012-12-17 02:34:06
【问题描述】:

我正在使用简单的代码:

import urllib2
response = urllib2.urlopen("http://www.mysite.com/getfile/4355")
output = open('myfile.zip','wb')
output.write(response.read())
output.close()

网络服务器是 IIS + ASP.NET MVC 4 它返回包含“application/octet-stream”内容类型的压缩文件的 FileResult。

问题是下载的 zip 文件已损坏 - 只有 4.1kB 大小,它必须是 24kB。当我直接在网络浏览器中输入网址时 - 它下载并打开正常。

您能否建议我的 Python 代码有什么问题?

编辑

尝试了其他两种方法 - 结果相同。

    import urllib
    urllib.urlretrieve(url, targetFile)

    h = httplib2.Http(".cache")
    response, content = h.request(url)
    with open(targetFile, 'wb') as f:
        f.write(content)

【问题讨论】:

    标签: python asp.net-mvc


    【解决方案1】:

    这是一个愚蠢的问题,但无论如何:我的控制器上有 [Authorize] 属性,因此无法执行匿名请求。

    删除它只允许我下载文件。

    还是谢谢。

    【讨论】:

      【解决方案2】:

      看看 python 'requests' 模块。你可以点安装它。示例代码为:

      >>>import requests
      >>>req_obj = requests.get("http://www.myexample.com/myfile.zip")
      >>>print len(req_obj)
      203456
      

      有关 API 的更多信息可以找到here...

      【讨论】:

        【解决方案3】:

        为了将来的参考,在 py3k 中你只需要使用 urllib.request.urlretrieve(the_url, the_filename) 来下载如下文件:

        import urllib.request
        
        url = 'http://www.example.com/the-file.zip'
        urllib.request.urlretrieve(url, 'filename.zip')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-07
          • 1970-01-01
          • 1970-01-01
          • 2022-01-07
          • 2012-06-15
          • 2020-05-12
          相关资源
          最近更新 更多