我们将在这里不断改写上一篇文章中的程序,并引入更高级的Python包,以写出更成熟的Python服务器。
# A messy HTTP server based on TCP socket 
 
import socket
 
# Address
HOST = ''
PORT = 8000
 
text_content = '''
HTTP/1.x 200 OK  
Content-Type: text/html
 
<head>
<title>WOW</title>
</head>
<html>
<p>Wow, Python Server</p>
<IMG src="test.jpg"/>
<form name="input" action="/" method="post">
First name:<input type="text" name="firstname"><br>
<input type="submit" value="Submit">
</form> 
</html>
'''
 
f = open('test.jpg','rb')
pic_content = '''
HTTP/1.x 200 OK  
Content-Type: image/jpg
 
'''
pic_content = pic_content + f.read()
 
# Configure socket
s    = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
 
# Serve forever
while True:
    s.listen(3)
    conn, addr = s.accept()                    
    request    = conn.recv(1024)         # 1024 is the receiving buffer size
    method     = request.split(' ')[0]
    src        = request.split(' ')[1]
 
    print 'Connected by', addr
    print 'Request is:', request
 
    # if GET method request
    if method == 'GET':
        # if ULR is /test.jpg
        if src == '/test.jpg':
            content = pic_content
        else: content = text_content
        # send message
        conn.sendall(content)
    # if POST method request
    if method == 'POST':
        form = request.split('rn')
        idx = form.index('')             # Find the empty line
        entry = form[idx:]               # Main content of the request
 
        value = entry[-1].split('=')[-1]
        conn.sendall(text_content + 'n <p>' + value + '</p>')
        ######
        # More operations, such as put the form into database
        # ...
        ######
    # close connection
    conn.close()SocketServer:
# use TCPServer
 
import SocketServer
 
HOST = ''
PORT = 8000
 
text_content = '''
HTTP/1.x 200 OK  
Content-Type: text/html
 
<head>
<title>WOW</title>
</head>
<html>
<p>Wow, Python Server</p>
<IMG src="test.jpg"/>
<form name="input" action="/" method="post">
First name:<input type="text" name="firstname"><br>
<input type="submit" value="Submit">
</form> 
</html>
'''
 
f = open('test.jpg','rb')
pic_content = '''
HTTP/1.x 200 OK  
Content-Type: image/jpg
 
'''
pic_content = pic_content + f.read()
 
# This class defines response to each request
class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # self.request is the TCP socket connected to the client
        request = self.request.recv(1024)
 
        print 'Connected by',self.client_address[0]
        print 'Request is', request
 
        method = request.split(' ')[0]
        src = request.split(' ')[1]
 
        if method == 'GET':
            if src == '/test.jpg':
                content = pic_content
            else: content = text_content
            self.request.sendall(content)
 
        if method == 'POST':
            form = request.split('rn')
            idx = form.index('')             # Find the empty line
            entry = form[idx:]               # Main content of the request
 
            value = entry[-1].split('=')[-1]
            self.request.sendall(text_content + 'n <p>' + value + '</p>')
            ######
            # More operations, such as put the form into database
            # ...
            ######
 
# Create the server
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Start the server, and work forever
server.serve_forever()<head> <title>WOW</title> </head> <html> <p>Wow, Python Server</p> <IMG src="test.jpg"/> <form name="input" action="/" method="post"> First name:<input type="text" name="firstname"><br> <input type="submit" value="Submit"> </form> </html>
SimpleHTTPServer: # Simple HTTPsERVER import SocketServer import SimpleHTTPServer HOST = '' PORT = 8000 # Create the server, SimpleHTTPRequestHander is pre-defined handler in SimpleHTTPServer package server = SocketServer.TCPServer((HOST, PORT), SimpleHTTPServer.SimpleHTTPRequestHandler) # Start the server server.serve_forever()
CGIHTTPServer: # A messy HTTP server based on TCP socket import BaseHTTPServer import CGIHTTPServer HOST = '' PORT = 8000 # Create the server, CGIHTTPRequestHandler is pre-defined handler server = BaseHTTPServer.HTTPServer((HOST, PORT), CGIHTTPServer.CGIHTTPRequestHandler) # Start the server server.serve_forever()
<head> <title>WOW</title> </head> <html> <p>Wow, Python Server</p> <IMG src="test.jpg"/> <form name="input" action="cgi-bin/post.py" method="post"> First name:<input type="text" name="firstname"><br> <input type="submit" value="Submit"> </form> </html>
我们创建一个cgi-bin的文件夹,并在cgi-bin中放入如下post.py文件,也就是我们的CGI脚本:
#!/usr/bin/env python # Written by Vamei import cgi form = cgi.FieldStorage() # Output to stdout, CGIHttpServer will take this as response to the client print "Content-Type: text/html" # HTML is following print # blank line, end of headers print "<p>Hello world!</p>" # Start of content print "<p>" + repr(form['firstname']) + "</p>"
第一行必须要有,以便告诉Python服务器,脚本所使用的语言 (我们这里的CGI是Python,当然也可以是别的语言,比如bash)。
cgi包用于提取request中提交的表格信息(我们暂时不深入cgi包)。脚本只负责将所有的结果输出到标准输出(使用print)。原文:http://blog.csdn.net/xufeng0991/article/details/40339289