Here are a few of the underlying modules for creating Web servers, the most important of which is Basehttpserver, and many frameworks and Web servers are created on their basis
Basic knowledge
To build a Web service, a basic server and a "processor"
is a must.
The underlying (WEB) server is a must-have stencil. Its role is to complete the necessary HTTP interaction on the client and server side.
In the Basehttpserver module you can find a basic class of servers called Httpserver.
Processors are simple software that handles the main "WEB services". They process the client's request and return the appropriate file,
Static text or a dynamic file generated by CGI. The complexity of the processor determines how complex your Web server is. Python
The standard library provides three different processor types.
The most basic, the most common is the vanilla processor, is named Basehttpresquesthandler, this can be in the basic
Found in the Basehttpserver module of the WEB server. In addition to obtaining client requests, no other processing work is performed.
So you have to do them yourself, which leads to the advent of myhttpd.py services.
For Simplehttprequesthandler in the Simplehttpserver module, built on
Basehttpresquesthandler, the standard get and head requests are executed directly. It's not perfect, but it's already
Can do some simple functions.
Finally, let's look at the Cgihttprequesthandler processor used in the Cgihttpserver module, which can get
Simplehttprequesthandler and provides support for post requests. It can invoke the CGI script to complete the request processing, or
To return the generated HTML script to the client.
basehttpserver provides basic Web services and processor classes, namely Httpserver and
Basehttprequesthandler
simplehttpserver contains simplehttprequesthandler classes that perform get and head requests
cgihttpserver includes processing post requests and executing Cgicgihttprequesthandler classes
Realize
#!/usr/bin/env python fromOsImportCurDir, Sep fromBasehttpserverImportBasehttprequesthandler, HttpserverclassMyHandler (basehttprequesthandler):defDo_get (self):Try: F= Open (CurDir + Sep +self.path) Self.send_response (200) Self.send_header ('Content-type', 'text/html') self.end_headers () Self.wfile.write (F.read ()) F.close ()exceptIOError:self.send_error (404, 'File not Found:%s'%Self.path)defMain ():Try: Server= Httpserver (("', 80), MyHandler)Print 'Welcome to the machine ...' Print 'Press ^c once or twice to quit'Server.serve_forever ()exceptKeyboardinterrupt:Print '^c received, shutting down server'server.socket.close ()if __name__=='__main__': Main ()
Python Web programming creates a Web server