summaryrefslogtreecommitdiffstats
path: root/Doc/howto
diff options
context:
space:
mode:
authorBerker Peksag <berker.peksag@gmail.com>2015-04-12 10:53:33 (GMT)
committerBerker Peksag <berker.peksag@gmail.com>2015-04-12 10:53:33 (GMT)
commit556e08e9b2016121e0984039c7087f52ba064297 (patch)
tree0c3dcc73147a7887a12a9d3ac75c9213fc12c914 /Doc/howto
parent48a724fa33143bcbab2228058d3f59e1813bd49c (diff)
parent9575e1891ff533318f6dd72ab6f6bd0f9a042014 (diff)
downloadcpython-556e08e9b2016121e0984039c7087f52ba064297.zip
cpython-556e08e9b2016121e0984039c7087f52ba064297.tar.gz
cpython-556e08e9b2016121e0984039c7087f52ba064297.tar.bz2
Issue #12955: Change the urlopen() examples to use context managers where appropriate.
Patch by Martin Panter.
Diffstat (limited to 'Doc/howto')
-rw-r--r--Doc/howto/urllib2.rst16
1 files changed, 8 insertions, 8 deletions
diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst
index abec053..01ae513 100644
--- a/Doc/howto/urllib2.rst
+++ b/Doc/howto/urllib2.rst
@@ -53,8 +53,8 @@ Fetching URLs
The simplest way to use urllib.request is as follows::
import urllib.request
- response = urllib.request.urlopen('http://python.org/')
- html = response.read()
+ with urllib.request.urlopen('http://python.org/') as response:
+ html = response.read()
If you wish to retrieve a resource via URL and store it in a temporary location,
you can do so via the :func:`~urllib.request.urlretrieve` function::
@@ -79,8 +79,8 @@ response::
import urllib.request
req = urllib.request.Request('http://www.voidspace.org.uk')
- response = urllib.request.urlopen(req)
- the_page = response.read()
+ with urllib.request.urlopen(req) as response:
+ the_page = response.read()
Note that urllib.request makes use of the same Request interface to handle all URL
schemes. For example, you can make an FTP request like so::
@@ -117,8 +117,8 @@ library. ::
data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data should be bytes
req = urllib.request.Request(url, data)
- response = urllib.request.urlopen(req)
- the_page = response.read()
+ with urllib.request.urlopen(req) as response:
+ the_page = response.read()
Note that other encodings are sometimes required (e.g. for file upload from HTML
forms - see `HTML Specification, Form Submission
@@ -183,8 +183,8 @@ Explorer [#]_. ::
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data, headers)
- response = urllib.request.urlopen(req)
- the_page = response.read()
+ with urllib.request.urlopen(req) as response:
+ the_page = response.read()
The response also has two useful methods. See the section on `info and geturl`_
which comes after we have a look at what happens when things go wrong.