python3实现的多线程httpserver

来源:互联网 发布:人种 知乎 编辑:程序博客网 时间:2024/06/08 02:18
http://www.perlcn.com/pythonbc/pythonjj/1289.html
python3实现的多线程httpserver
2013年07月13日 ⁄ Python进阶 ⁄ 共 1239字 ⁄ 评论数 1 ⁄ 被围观 568 次+

我们主要使用python3提供的http模块来实现一个python的http服务器。在浏览器的地址栏里面输入http://127.0.0.1:8080就可以查看这个程序的运行结果了。
另外在这个程序里,我们为了提供性能,使用了多线程的技术。主要是使用socketserver提供的ThreadingMixIn模块来实现的,具体如下下面的代码所示:

  1. from http.server import BaseHTTPRequestHandler
  2. from http.server import HTTPServer
  3. from socketserver import ThreadingMixIn
  4.  
  5. hostIP = ''
  6. portNum = 8080
  7. class mySoapServer( BaseHTTPRequestHandler ):
  8.     def do_head( self ):
  9.         pass
  10.    
  11.     def do_GET( self ):
  12.         try:
  13.             self.send_response( 200, message = None )
  14.             self.send_header( 'Content-type''text/html' )
  15.             self.end_headers()
  16.             res = '''
  17.            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  18.            <HTML>
  19.            <HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
  20.            <META content="text/html; charset=gb2312" http-equiv=Content-Type>
  21.            </HEAD>
  22.            <BODY>
  23.            Hi, www.perlcn.com is a good site to learn python!
  24.            </BODY>
  25.            </HTML>
  26.            '''
  27.             self.wfile.write( res.encode( encoding = 'utf_8', errors = 'strict' ) )
  28.         except IOError:
  29.             self.send_error( 404, message = None )
  30.    
  31.     def do_POST( self ):
  32.         try:
  33.             self.send_response( 200, message = None )
  34.             self.send_header( 'Content-type''text/html' )
  35.             self.end_headers()
  36.             res = '''
  37.            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  38.            <HTML>
  39.            <HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
  40.            <META content="text/html; charset=gb2312" http-equiv=Content-Type>
  41.            </HEAD>
  42.            <BODY>
  43.            Hi, www.perlcn.com is a good site to learn python!
  44.            </BODY>
  45.            </HTML>
  46.            '''
  47.             self.wfile.write( res.encode( encoding = 'utf_8', errors = 'strict' ) )
  48.         except IOError:
  49.             self.send_error( 404, message = None )
  50.  
  51. class ThreadingHttpServer( ThreadingMixIn, HTTPServer ):
  52.     pass
  53.      
  54. myServer = ThreadingHttpServer( ( hostIP, portNum ), mySoapServer )
  55. myServer.serve_forever()
  56. myServer.server_close()

在浏览器的地址栏里面输入http://127.0.0.1:8080,测试结果如下:
127.0.0.1 - - [13/Jul/2013 15:22:38] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2013 15:22:38] "GET /favicon.ico HTTP/1.1" 200 -

原创粉丝点击