Created
October 26, 2011 14:18
-
-
Save ojii/1316491 to your computer and use it in GitHub Desktop.
requests vs sockets
This file contains 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
URL = 'http://httpbin.org/status/200' | |
def check(status_code, headers, content): | |
assert status_code == 200 | |
assert headers['Content-Length'] == '0' | |
assert headers['Content-Type'] == 'text/html; charset=utf-8' | |
assert headers['Connection'] == 'close' | |
print 'OK' |
This file contains 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 requests | |
from common import URL, check | |
def run(): | |
response = requests.get(URL) | |
return response.status_code, response.headers, response.content | |
if __name__ == '__main__': | |
check(*run()) |
This file contains 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 socket | |
from common import URL, check | |
def run(): | |
protocol, rest = URL.split('://', 1) | |
host, path = rest.split('/', 1) | |
path = '/%s' % path | |
s = socket.socket() | |
s.connect((host, 80)) | |
s.send('GET %s HTTP/1.1\r\nHost: %s\r\n\r\n' % (path, host)) | |
data = '' | |
while True: | |
block = s.recv(1024) | |
data += block | |
if not block: | |
break | |
s.close() | |
raw_headers, content = data.split('\r\n\r\n') | |
raw_status, raw_headers = raw_headers.split('\r\n', 1) | |
status = raw_status[len('HTTP/1.1 '):] | |
status_code = int(status.split(' ', 1)[0]) | |
headers = dict([[x.strip() for x in line.split(':', 1)] for line in raw_headers.split('\r\n') if line.strip()]) | |
return status_code, headers, content | |
if __name__ == '__main__': | |
check(*run()) |
This file contains 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
jonas@jonas-Serval-Professional:~/playground/pyhttp$ time python example_sockets.py | |
OK | |
real 0m0.278s | |
user 0m0.028s | |
sys 0m0.008s | |
jonas@jonas-Serval-Professional:~/playground/pyhttp$ time python example_requests.py | |
OK | |
real 0m0.604s | |
user 0m0.152s | |
sys 0m0.028s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment