I am trying to use http-parser and write the response to a file following the example here. This is what I am trying to do, I changed the GET request to request an image and then trying to save it to a file:
open('image.jpg', 'wb').write(p.body_file().read())
But the file has zero bytes. What am I missing here?
Complete code:
#!/usr/bin/env python
import socket
from http_parser.http import HttpStream
from http_parser.reader import SocketReader
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('www.linux-mag.com', 80))
s.send("GET http://www.linux-mag.com/s/i/topics/tux.jpg HTTP/1.1\r\nHost: www.linux-mag.com\r\n\r\n")
r = SocketReader(s)
p = HttpStream(r)
print p.body_file()
open('image.jpg', 'wb').write(p.body_file().read())
finally:
s.close()
if __name__ == "__main__":
main()
It turns out that I needed to
sudothe script. I didsudo python <script>it works fine.