Last active
May 27, 2017 15:57
-
-
Save chimeno/2e2e78dce1d07e5f5f49424299cec27f to your computer and use it in GitHub Desktop.
averages carto
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| import urllib.parse | |
| import sys | |
| @asyncio.coroutine | |
| def count_things(url): | |
| url = urllib.parse.urlsplit(url) | |
| if url.scheme == 'https': | |
| connect = asyncio.open_connection(url.hostname, 443, ssl=True) | |
| else: | |
| connect = asyncio.open_connection(url.hostname, 80) | |
| reader, writer = yield from connect | |
| query = ('GET {path} HTTP/1.1\r\n' | |
| 'Host: {hostname}\r\n' | |
| '\r\n').format(path=url.path or '/', hostname=url.hostname) | |
| writer.write(query.encode('utf-8')) | |
| num_lines = 0 | |
| total_tips = 0 | |
| while True: | |
| line = yield from reader.readline() | |
| if not line: | |
| break | |
| line = line.decode('utf-8').rstrip() | |
| if line and line[0].isdigit(): # Start the data content | |
| tip_amount = float(line.split(',')[15]) # tip_amount column | |
| num_lines +=1 | |
| total_tips += tip_amount | |
| writer.close() | |
| print(total_tips/num_lines) | |
| url = sys.argv[1] | |
| loop = asyncio.get_event_loop() | |
| task = asyncio.ensure_future(count_things(url)) | |
| loop.run_until_complete(task) | |
| loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment