0

I want to download a zip file using python, I am getting the while running following code

import requests, zipfile, StringIO

zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
r = None
try:
 r = requests.get(zip_file_url, stream=True)

except requests.exceptions.ConnectionError:
 print "Connection refused"

z = zipfile.ZipFile(StringIO.StringIO(r.content))

How should I declare "r"?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Mukesh Bharsakle
  • 403
  • 1
  • 4
  • 17

1 Answers1

1

You should not declare r. In python you don't need to declare variables.

It is not clear from your question, but I bet that your output includes que "Connection refused" string. In that case, there's no need to try to access r.content: as the connection has been refused, nothing can be there. Just perform a proper error management:

import requests, zipfile, StringIO

zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
try:
    r = requests.get(zip_file_url, stream=True)
except requests.exceptions.ConnectionError:
    print "Connection refused"
    exit() # That's an option, just finish the program

if r is not None:
    z = zipfile.ZipFile(StringIO.StringIO(r.content))
else:
    # That's the other option, check that the variable contains
    # a proper value before referencing it.
    print("I told you, there was an error while connecting!")
Poshi
  • 5,332
  • 3
  • 15
  • 32
  • Thank you! the above error is gone, but now I am always getting Connection refused!! – Mukesh Bharsakle Jul 04 '18 at 09:48
  • I tried to open that link in the browser and in the command line and both worked. Check is there is some firewall or network configuration preventing you to reach that server. Can you download it using a browser in the same machine where you get the "Connection refused" error? – Poshi Jul 04 '18 at 10:39