Pythonweb Server Programming (iii)

Source: Internet
Author: User

Web static server-display required pages
#Coding=utf-8ImportSocket fromMultiprocessingImportProcessImportRedefhandleclient (clientsocket):'Service for a client with a new process'RecvData= CLIENTSOCKET.RECV (2014) Requestheaderlines=Recvdata.splitlines () forLineinchRequestheaderlines:Print(line) Httprequestmethodline=Requestheaderlines[0] GetFileName= Re.match ("[^/]+(/[^ ]*)", Httprequestmethodline). Group (1)    Print("file name is ===>%s"%getfilename)#For Test    ifGetFileName = ='/': GetFileName= DocumentRoot +"/index.html"    Else: GetFileName= DocumentRoot +GetFileNamePrint("file name is ===2>%s"%getfilename)#For Test    Try: F=Open (GetFileName)exceptIoerror:responseheaderlines="http/1.1 404 Not found\r\n"Responseheaderlines+="\ r \ n"Responsebody="====sorry, File not found===="    Else: Responseheaderlines="http/1.1 ok\r\n"Responseheaderlines+="\ r \ n"Responsebody=F.read () f.close ( )finally: Response= Responseheaderlines +responsebody clientsocket.send (response) Clientsocket.close ()defMain ():'as the main control entrance of the program'ServerSocket=Socket.socket (socket.af_inet, socket. SOCK_STREAM) serversocket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR,1) Serversocket.bind ("", 7788)) Serversocket.listen (10)     whiletrue:clientsocket,clientaddr=serversocket.accept () clientp= Process (target = handleclient, args =(Clientsocket,)) Clientp.start () Clientsocket.close ( )#Configure the server hereDocumentRoot ='./html'if __name__=='__main__': Main ()

 
Web static server-use class
#Coding=utf-8ImportSocketImportSYS fromMultiprocessingImportProcessImportReclassWsgiserver (object): AddressFamily=socket.af_inet SocketType=socket. Sock_stream requestqueuesize= 5def __init__(self, server_address):#Create a TCP socketSelf.listensocket =Socket.socket (Self.addressfamily,self.sockettype)#allows reuse of the last socket bound PortSelf.listenSocket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)        #bindingSelf.listenSocket.bind (server_address)#become passive, and set the length of the queueSelf.listenSocket.listen (self.requestqueuesize)defServeforever (self):'looping the Web server, waiting for the client to link and servicing the client'         whileTrue:#waiting for new clients to arriveSelf.clientsocket, client_address =self.listenSocket.accept ()#Method 2, multi-process server, concurrent server on multiple clientsNewclientprocess = Process (target =self.handlerequest) Newclientprocess.start ()#because this socket +1 is created in a new process, it needs to be subtracted in the main process, called once closeself.clientSocket.close ()defHandleRequest (self):'Service for a client with a new process'RecvData= SELF.CLIENTSOCKET.RECV (2014) Requestheaderlines=Recvdata.splitlines () forLineinchRequestheaderlines:Print(line) Httprequestmethodline=Requestheaderlines[0] GetFileName= Re.match ("[^/]+(/[^ ]*)", Httprequestmethodline). Group (1)        Print("file name is ===>%s"%getfilename)#For Test        ifGetFileName = ='/': GetFileName= DocumentRoot +"/index.html"        Else: GetFileName= DocumentRoot +GetFileNamePrint("file name is ===2>%s"%getfilename)#For Test        Try: F=Open (GetFileName)exceptIoerror:responseheaderlines="http/1.1 404 Not found\r\n"Responseheaderlines+="\ r \ n"Responsebody="====sorry, File not found===="        Else: Responseheaderlines="http/1.1 ok\r\n"Responseheaderlines+="\ r \ n"Responsebody=F.read () f.close ( )finally: Response= Responseheaderlines +responsebody self.clientSocket.send (response) Self.clientSocket.close ()#set the port of the serverServeraddr = (HOST, PORT) ="', 8888#path to set Server service static resourcesDocumentRoot ='./html'defMakeserver (SERVERADDR): Server=wsgiserver (SERVERADDR)returnServerdefMain (): httpd=makeserver (SERVERADDR)Print('Web server:serving HTTP on port%d ... \ n'%PORT) httpd.serveforever ()if __name__=='__main__': Main ()

Pythonweb Server Programming (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.