God, to take the exam, to the final exam, today the final version of the Python build Web code first write down here. The detailed process is not written first.
This time is based on the previous rewrite Httpserver and Basehttprequesthandler, mainly using Python to provide
Socket is programmed to receive and respond to the message, and then multiple threads are introduced to process the client
The ability to dynamically generate pages based on parameters passed by the client.
The main steps are as follows:
I. Rewrite Httpserver and Basehttprequesthandler
Python socket Programming process (server side):
1. The first step is to create the socket object. Call the socket constructor. Such as:
Socket = Socket.socket (family, type)
The family parameter represents the address family, which can be either af_inet or Af_unix. The Af_inet family includes the Internet
Address, the Af_unix family is used for interprocess communication on the same machine.
The type parameter represents a socket type, which can be sock_stream (stream sockets) and Sock_dgram (number
Reportedly sockets).
2. The second step is to bind the socket to the specified address. This is done through the bind method of the Socket object:
Socket.bind (Address)
The socket created by AF_INET, the address must be a two-element tuple, and the format is
(Host,port). Host, Port represents the port number. If the port number is in use, the host name is not positive
or the port is reserved, the Bind method throws an Socket.error exception.
3. The third step is to receive the connection request using the Listen method of the socket socket.
Socket.listen (Backlog)
The backlog specifies the maximum number of clients that are allowed to connect to the server. It has a value of at least 1. After you receive the connection request,
These requests need to be queued, and if the queue is full, the request is rejected.
4. The fourth step is that the server socket waits for the client to request a connection through the socket's accept method.
Connection, address = socket.accept ()
When the Accept method is called, the socket is in the "Waiting" state. When a customer requests a connection, the method establishes a link
And then return to the server. The Accept method returns a tuple containing two elements (connection,address).
The first element, connection, is the new socket object, which the server must communicate with the client;
The address of an element is the Internet addresses of the customers.
5. The fifth step is the processing stage where the server and the client communicate via the Send and Recv methods (transmit data). Clothing
Send message to the client in string form. The Send method returns the characters that were sent
Number. The server uses the Recv method to receive information from the customer. When calling recv, the server must specify a
An integer that corresponds to the maximum amount of data that can be received by this method call. Recv method when receiving data
Enters the "blocked" state and finally returns a string that represents the received data. If the number of messages sent
The data will be truncated if the amount exceeds the allowable recv. The excess data will be buffered on the receiving side. Call later
Recv, the extra data is removed from the buffer (and, since the last call to Recv, the customer may send
any other data).
6. When the transfer is complete, the server calls the Close method of the socket to close the connection.
The entire code block is as follows:
The comments are a bit messy, Chinese and English combined.
test.py
#-*-coding:utf-8-*-import basehttpserverimport osimport socketimport subprocessimport threadingfrom datetime Import Datetimeclass serverexception (Exception): Pass # # rewrite Httpserver and basehttprequesthandler, mainly using Python to provide # The socket is programmed to receive and respond to the message, then the multi-threading is introduced to process the request from the client's # side, and finally the function of generating the page dynamically based on the parameters passed by the client is implemented. # Step1:rewrite Httpserver and Basehttprequesthandlerclass httpserver:def __init__ (self, serveraddr, RequestHandler): Self.serveraddr = Serveraddr Self.requesthandler = RequestHandler def serve_forever (self): # 1. Create socket object (object), call socket create function Server_sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # 1family=af_inet,type=sock_stream Server_sock.bind (SELF.SERVERADDR) # 2. Call socket bind, aim to bind socket to pointed address # address must be a two-elements Yuanzu, style is (host, PO RT) # Host stands for port number. If port number is in using #, host name is WROng or port number has been saved, bind the "would # Bring Socket.error Yi Chang Server_sock.listen (10) # 3. Using socket ' s listen-to-Receive connect request # Listen Parament Backlog=10:point allow No. more than TS # can connect to server. It value at least is 1. When received # request, those requests need PAI dui,if list full, then refuse request while True: print ' Waiting for connection ... ' clientsock, addr = Server_sock.accept () # 4. Server socket wait for client to request a connection # when call accept () function, socket would come into "wat ing "# states. When client request connection,function Create # Connection and return server: # Accept function return with both elements # (connection, address)., the first connection is new socket ' s # object, server must through it to Tong Xin with client. # The second ElemENT address is clients ' Internet address print ' Received from: ', addr thread = Threading. Thread (Target=self.startthread, args= (Clientsock, addr,)) Thread.setdaemon (True) Thread.Start () # handler = RequestHandler (Clientsock, addr,self) server_sock.close () def startthread (self, clientsock, a DDR): Handler = RequestHandler (Clientsock, addr, self) class httprequesthandler:bufsize = 1024x768 def __init__ (s Elf, Clientsock, addr): Self.cliensock = clientsock self.client_address = addr Self.date_time_string = DateTime.Now () self.analyze () # HTTP head part analyze def analyze (self): # receive dates, BufSize poin TS to read dates num one time "": Type Self:object "" "Data = Self.cliensock.recv (SELF.BUFSI Ze) # print ' Receive------->%s\n%s '% (DateTime.Now (), data) # Chrome sometimes would send both request cons IST, tne second is null, reason is Unknow if Data.repalce ("", "") = = "": print "data is null" return data = Data.split ( ' \ r \ n ') # First line is "get/something.html?a=1&b=2 http/1.1 firstline = data[0] arr = firstline. Split (') Self.command = arr[0] Self.protocol = arr[2] if '? ' in arr[1]: # path put Absol Ute-Self.path, self.paramstr = arr[1].spilt ('? ') Else:self.path = arr[1] Self.paramstr = None # Put the remain of head information in Hea Des ' s dictionary in the "The" of key value # ACCEPT-LANGUAGE:ZH-CN # connection:keep-alive # host:localhost # accept-encoding:gzip, deflate self.headers = {} for Line In data[1:]: "If ': ' in line:key, value = Line.split (': ', 1) self.he Aders[key] = value # Call function to deal with, this FuNction have come in the first self.do_get () # Time.sleep ($) # when this function receive Data, first Feng Li data # char string as th rule of ' \ r \ n ' and ti qu first line, which is "get/so mething.html?a=1&b=2 http/1.1 # Then analyze it, put it to the variable # path http_response = "HTTP /1.1 "Def send_response (Self, status): if status = = 200:self.http_response + +" + "+" OK " elif Status = = 404:self.http_response + = "+" + "+" not Found "self.http_response + = ' \ r \ n ' # "Content_Type", "text/html" # "Content-length", Length def send_heade (self, Key, value): Self.http_response + = str (key) + ":" + str (value) + ' \ r \ n ' def end_headers (self): self.http_response + = ' \ r \ n ' def write (self, Page): Self.http_response + = str (page) self.clientsock.send (self.http_response) self.cliensock.close () # those FunctiONS is pin zhuang http_response char string # As the rule of response head Styleclass RequestHandler (basehttpserve R.basehttprequesthandler): "" "dealt with and return page" "" # Page Model page = "'
calc.py
Import sysparamstr = Sys.argv[1]paramarr = Paramstr.split (' & ') paramdict = {}for param in Paramarr: key, value = PA Ram.split (' = ') Paramdict[key] = valueprint "
Index.html
<! DOCTYPE html>Run effect
Prepare for the final exam ....
Final version of the Web (Python implementation)