Reputation: 13
Was wondering if anyone could enplain the differences between the following? Also why would you use one over the other?
urllib.request.urlopen
urllib.request.Request
HTTPConnection.request
I'm using python 3.2. I'm trying to understand how to use python with the web but the documentation is not that helpful at explaining things.
Upvotes: 1
Views: 161
Reputation: 2754
urllib.request.urlopen sends a request to a server and returns the result. This is usually the file/website you requested. So the code below will print the content of the requested file:
import urllib.request
r = urllib.request.urlopen('http://example.com/some_file.stuff')
print(r.read())
But urllib.request.Request just represents the data which would be sent to the server to get the data you want. So the example above could be rewritten like that:
import urllib.request
req = urllib.request.Request('http://example.com/some_file.stuff')
r = urllib.request.urlopen(req)
print(r.read())
HTTPConnection does something different. It just connects to the server and then gives you the responsibility to do the rest (whatever you want to do on the Server, requesting files etc...) wihtout requesting a specific file. While urlopen opens and fetches the file you requested. So HTTPConnection is more general but for most cases urllib.request.urlopen should be enough.
Upvotes: 1