python简单网页服务器示例
参考:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832689740b04430a98f614b6da89da2157ea3efe2000
代码:
hello.py
1 #!/usr/bin/python 2 # coding: utf-8 3 4 # hello.py 5 def application(environ, start_response): 6 start_response('200 OK', [('Content-Type', 'text/html')]) 7 return '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
server.py
1 #!/usr/bin/python 2 # coding: utf-8 3 4 # server.py 5 from wsgiref.simple_server import make_server 6 from hello import application 7 8 # create server, ip is empty, port is 8000, handle function is application 9 httpd = make_server('', 8000, application) 10 print "Serving HTTP on port 8000..." 11 # start listen http request 12 httpd.serve_forever()
使用了模块wsgiref。它实现了wsgi接口,我们只需要定一个wsgi处理函数来处理得到的请求就可以了。
用python来实现这些看似很复杂的实例程序,非常简单,这都得益于python强大的库。