0

I am fetching data from a URL using urllib2.urlopen:

from urllib2 import urlopen
...
conn = urlopen(url)
data = conn.read()
conn.close()

Suppose the data did not "come out" as I had expected.

What would be the best method for me to read it again?

I am currently repeating the whole process (open, read, close).

Is there a better way (some sort of connection-refresh perhaps)?

barak manos
  • 29,648
  • 10
  • 62
  • 114

3 Answers3

2

When you call urlopen on a URL, Python makes an HTTP GET request and returns the response; each of these request-response pairs are by nature separate connections. You have to repeat the process for every URL you want to request, although you don't really have to close your urlopen response.

Community
  • 1
  • 1
Mark Ignacio
  • 421
  • 3
  • 8
  • Thank you for the detailed answer. BTW, the "although you don't really have to close your urlopen response" statement is not correct according to the redirected link. – barak manos Aug 14 '14 at 21:06
2

No, repeating the process is the only way to get new data.

rhodysurf
  • 357
  • 1
  • 4
  • 12
0

you chould close urllib after used to refresh when you open early

try:

import json, urllib while 1 : url='http://project/JsonVanner.php' response = urllib.urlopen(url) data = json.loads(response.read()) for x in data : print x['Etat'] if (x['Etat'] == 'OFF'): print('vanne fermer') print((int(x['IDVanne'])*10)+0) else : print('vanne ouverte') print((int(x['IDVanne'])*10)+1) response.close()

radhouen
  • 21
  • 9