Created
October 25, 2011 01:37
-
-
Save davidbgk/1311056 to your computer and use it in GitHub Desktop.
A very simple HTTP server in Python using wsgiref.simple_server
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
from cgi import parse_qs | |
from wsgiref.simple_server import make_server | |
def simple_app(environ, start_response): | |
status = '200 OK' | |
headers = [('Content-Type', 'text/plain')] | |
start_response(status, headers) | |
if environ['REQUEST_METHOD'] == 'POST': | |
request_body_size = int(environ.get('CONTENT_LENGTH', 0)) | |
request_body = environ['wsgi.input'].read(request_body_size) | |
d = parse_qs(request_body) # turns the qs to a dict | |
return 'From POST: %s' % ''.join('%s: %s' % (k, v) for k, v in d.iteritems()) | |
else: # GET | |
d = parse_qs(environ['QUERY_STRING']) # turns the qs to a dict | |
return 'From GET: %s' % ''.join('%s: %s' % (k, v) for k, v in d.iteritems()) | |
httpd = make_server('', 1337, simple_app) | |
print "Serving on port 1337..." | |
httpd.serve_forever() |
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
$ python server.py | |
Serving on port 1337... | |
1.0.0.127.in-addr.arpa - - [25/Oct/2011 10:36:10] "POST / HTTP/1.1" 200 24 | |
1.0.0.127.in-addr.arpa - - [25/Oct/2011 10:36:11] "GET /?foo=bar HTTP/1.1" 200 22 | |
$ curl http://localhost:1337/?foo=bar | |
From GET: foo: ['bar'] | |
$ curl -d baz=quux http://localhost:1337/ | |
From POST: baz: ['quux'] |
C'est pas la similarité, c'est juste la lisibilité de Python qui peut te choquer par rapport à Ruby :ppp
Ça veut dire que tu me provoques pour que je te fasse une version Ruby ?
C'est quoi tes contraintes de dépendances ? juste la core-lib, aussi la standard-lib ou bien carrément des paquets externes ?
Nan c'est bon c'était juste pour te taquiner, tu démarres trop vite ;-)
$ python -m SimpleHTTPServer 8080
🤘
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
C'est génial, comme la similarité entre Rack (Ruby) et WSGI (Python) me permet de comprendre chaque ligne de ce code alors que je n'y connais rien à Python ;-)