asyncio doc: add an client example using streams
authorVictor Stinner <victor.stinner@gmail.com>
Thu, 23 Jan 2014 10:25:48 +0000 (11:25 +0100)
committerVictor Stinner <victor.stinner@gmail.com>
Thu, 23 Jan 2014 10:25:48 +0000 (11:25 +0100)
Doc/library/asyncio-stream.rst

index 19ac103a66e0873a3a3a9c00cf777b6bb5c1c0ed..e457fe58da561758110ea0931d2cdfd12deac043 100644 (file)
@@ -205,3 +205,38 @@ StreamReaderProtocol
 
        XXX
 
+
+Example
+=======
+
+Simple example querying HTTP headers of the URL passed on the command line::
+
+    import asyncio
+    import urllib.parse
+    import sys
+
+    @asyncio.coroutine
+    def print_http_headers(url):
+        url = urllib.parse.urlsplit(url)
+        reader, writer = yield from asyncio.open_connection(url.hostname, 80)
+        query = ('HEAD {url.path} HTTP/1.0\r\n'
+                 'Host: {url.hostname}\r\n'
+                 '\r\n').format(url=url)
+        writer.write(query.encode('latin-1'))
+        while True:
+            line = yield from reader.readline()
+            if not line:
+                break
+            line = line.decode('latin1').rstrip()
+            if line:
+                print('HTTP header> %s' % line)
+
+    url = sys.argv[1]
+    loop = asyncio.get_event_loop()
+    task = asyncio.async(print_http_headers(url))
+    loop.run_until_complete(task)
+
+Usage::
+
+    python example.py http://example.com/path/page.html
+