我们主要使用python3提供的http模块来实现一个python的http服务器。在浏览器的地址栏里面输入http://127.0.0.1:8080就可以查看这个程序的运行结果了。
另外在这个程序里,我们为了提供性能,使用了多线程的技术。主要是使用socketserver提供的ThreadingMixIn模块来实现的,具体如下下面的代码所示:
-
from http. server import BaseHTTPRequestHandler
-
from http. server import HTTPServer
-
from socketserver import ThreadingMixIn
-
-
hostIP = ''
-
portNum = 8080
-
class mySoapServer ( BaseHTTPRequestHandler ):
-
def do_head ( self ):
-
pass
-
-
def do_GET ( self ):
-
try:
-
self. send_response ( 200, message = None )
-
self. send_header ( 'Content-type', 'text/html' )
-
self. end_headers ( )
-
res = '' '
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
<HTML>
-
<HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
-
<META content="text/html; charset=gb2312" http-equiv=Content-Type>
-
</HEAD>
-
<BODY>
-
Hi, www.perlcn.com is a good site to learn python!
-
</BODY>
-
</HTML>
-
' ''
-
self. wfile. write ( res. encode ( encoding = 'utf_8', errors = 'strict' ) )
-
except IOError:
-
self. send_error ( 404, message = None )
-
-
def do_POST ( self ):
-
try:
-
self. send_response ( 200, message = None )
-
self. send_header ( 'Content-type', 'text/html' )
-
self. end_headers ( )
-
res = '' '
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
<HTML>
-
<HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
-
<META content="text/html; charset=gb2312" http-equiv=Content-Type>
-
</HEAD>
-
<BODY>
-
Hi, www.perlcn.com is a good site to learn python!
-
</BODY>
-
</HTML>
-
' ''
-
self. wfile. write ( res. encode ( encoding = 'utf_8', errors = 'strict' ) )
-
except IOError:
-
self. send_error ( 404, message = None )
-
-
class ThreadingHttpServer ( ThreadingMixIn, HTTPServer ):
-
pass
-
-
myServer = ThreadingHttpServer ( ( hostIP, portNum ), mySoapServer )
-
myServer. serve_forever ( )
-
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 -