[Tutor] Single line webserver [was: Tutor Digest, Vol 93, Issue 38]

Steven D'Aprano steve at pearwood.info
Tue Nov 8 18:07:45 CET 2011


Rich Lovely wrote:

> I'd like to draw your attention to my original message: "a google
> search is similarly lacking in relevant results."  Shouldn't it be
> clear from how easy it is to find SimpleHttp that it clearly /isn't/
> what I'm looking for? Perhaps I should have mentioned that, but I
> thought I'd made it clear I'd tried a websearch.

Yes, you should have mentioned that SimpleHttp was not the one-liner you 
were looking for. That would have been useful to know :)

Your request was for a one-liner web server, and you claimed to have 
done a search which came up with nothing relevant. Since a simple search 
did in fact come up with an apparently relevant one-liner, the most 
obvious conclusions were that your search skills are very lousy, or that 
you were mistaken (i.e. lying) about having attempted to search first. 
Coming from an apparent first-time poster with no reputation I was aware 
of, neither would have surprised me. I'm glad that neither is actually 
the case.


> The code I remember was a Socket-based webserver, written in one -
> albeit rather long - line.

That would have been useful information to have mentioned at the time.

For what little it's worth, here's a 15 line socket-based web server:


import socket
template = ('HTTP/1.0 200 OK\n\n<html><head><title>Welcome %s!</title>'
   '</head><body><h1>Header...</h1>...and body.<br>Your request was: '
   '"%s"</body></html>')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 8080))
sock.listen(1)
print "Listening on port 8080"
while True:
     client, address = sock.accept()
     cfile = client.makefile('rw', 0)
     cfile.write(template % (str(address), cfile.readline().strip()))
     cfile.close()
     client.close()


Save this as "web.py", run "python web.py", and then in your browser go 
to http://localhost:8080

Turning this into a one-liner is left as an exercise. This may be useful:

http://pauldotcom.com/2011/10/python-one-line-shell-code.html



P.S. I note you're replying to the digest. Thank you for trimming your 
reply, rather than including the entire digest, but please note the 
request at the top of each digest:

     When replying, please edit your Subject line so it is
     more specific than "Re: Contents of Tutor digest..."



-- 
Steven


More information about the Tutor mailing list