Because of the various Python frameworks have implemented the WSGI interface, so the versatility is very wide.
During the commissioning process, one of the letters was misspelled and engaged for one hours.
It seems that the Python-brought editor is not highlighted and uncomfortable.
You can see it in the editor with the hint. :)
Webserver. PY
ImportSocketImportStringioImportSYSclassWsgiserver (object): Address_family=socket.af_inet Socket_type=socket. Sock_stream request_queue_size= 1def __init__(self, server_address):#Create a listening socketSelf.listen_socket = Listen_socket =Socket.socket (self.address_family, Self.socket_type)#Allow to reuse the same addressListen_socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) #BindListen_socket.bind (server_address)#ActiveListen_socket.listen (self.request_queue_size)#Get Server host name and PortHost, Port = Self.listen_socket.getsockname () [0:2] Self.server_name=Socket.getfqdn (host) Self.server_port=Port#Return headers set by Web Framework/web applicationSelf.headers_set = [] defSet_app (self, application): Self.application=ApplicationdefServe_forever (self): Listen_socket=Self.listen_socket whileTrue:#New Client ConnectionSelf.client_connection, client_address =listen_socket.accept ()#Handle one request and close the client connection. Then #loop over to wait for another client connectionself.handle_one_request ()defhandle_one_request (self): Self.request_data= Request_data = SELF.CLIENT_CONNECTION.RECV (1024) #Print formatted request data a la ' curl-v ' Print("'. Join ('< {line} \ n'. Format (line=Line ) forLineinchRequest_data.splitlines ())) Self.parse_request (request_data)#Construct Environment dictionary using requst dataenv =Self.get_environ ()#It ' s time to call our application callable and get #Back a result that would become HTTP response body Print 'self.application: ********************', self.application result=self.application (env, Self.start_response)#Construct a response and send it back to the clientself.finish_response (Result)defparse_request (self, text): Request_line=text.splitlines () [0] Request_line= Request_line.rstrip ('\ r \ n') #Break off the request line into components(Self.request_method,#GETSelf.path,#/helloSelf.request_version#http/1.1) =Request_line.split ()defGet_environ (self): env= {} #The following code snippet does not follow PEP8 conventions #But it's formatted the IT's for demonstration purposes #To emphasize the required variables and their values # #Required WSGI Variablesenv['wsgi.version'] = (1, 0) env['Wsgi.url_scheme'] ='http'env['Wsgi.input'] =Stringio.stringio (self.request_data) env['wsgi.errors'] =Sys.stderr env['Wsgi.multithread'] =False env['wsgi.multiprocess'] =False env['wsgi.run_once'] =False#Required CGI Variablesenv['Request_method'] = Self.request_method#GETenv['Path_info'] = Self.path#/helloenv['server_name'] = Self.server_name#localhostenv['Server_port'] = str (self.server_port)#8888 returnEnvdefStart_response (self, status, Response_headers, exc_onfo=None):#Add Necessary Server headersServer_headers = [ ('Date','Tue, 12:54:48 GMT'), ('Server','Wsgiserver'),] self.headers_set= [Status, Response_headers +Server_headers]#To adhere to WSGI specification the Start_response must return #a ' write ' callable. We simplicity ' s sake we ' ll ignore that detail #For now . #return Self.finish_response deffinish_response (self, result):Try: status, Response_headers=Self.headers_set Response='http/1.1 {status}\r\n'. Format (status=status) forHeaderinchResponse_headers:response+='{0}: {1}\r\n'. Format (*header) Response+='\ r \ n' forDatainchResult:response+=Data#Print Formatted response data a la ' curl-v ' Print("'. Join ('> {line}\n'. Format (line=Line ) forLineinchResponse.splitlines ())) Self.client_connection.sendall (response)finally: Self.client_connection.close () server_address= (HOST, PORT) ="', 8888defMake_server (server_address, application): Server=wsgiserver (server_address) Server.set_app (application)returnServerif __name__=='__main__': ifLen (SYS.ARGV) < 2: Sys.exit ('provide a WSGI Application object as Module:callable') App_path= Sys.argv[1] module, application= App_path.split (':') Module=__import__(module) application=getattr (module, application) httpd=Make_server (server_address, application) httpd.serve_forever ()Print("wsgiserver:serving HTTP on port {port}...\n". Format (port=PORT))
wsgiapp.py
defapp (environ, start_response):"""A barebones WSGI application. This is a starting a-own Web Framework:)"""Status='OK'response_headers= [('Content-type','Text/plain')] Start_response (status, Response_headers)return['Hello World from a simple WSGI application!\n']
To run the command:
Python webserver.py Wsgiapp:app
Results:
Wsgi Server Practice Two--WSGI server that practices a basic function