Wednesday, July 04, 2012

Web Service by Python

To develop web service with Python is really simple.
Here are 2 examples.

Demo 1, hello world.

#!/usr/bin/env python27
#!/usr/bin/python27
from wsgiref.simple_server import make_server
# A relatively simple WSGI application. It's going to print out Hello,
def simple_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    ret = 'Hello Friend.'
    return ret
httpd = make_server('', 7001, simple_app)
print "Serving on port 7001..."
httpd.serve_forever()


Demo 1.1, Print out the environment parameters.

from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    ret = ["%s: %s\n" % (key, value)
           for key, value in environ.iteritems()]
    return ret
httpd = make_server('', 7100, simple_app)
print "Serving on port 7100..."
httpd.serve_forever()

Post a Comment