Python web server and Pythonweb Server
1. browser request dynamic page process 2. WSGI
Python Web Server Gateway Interface (or WSGI for short, read as "wizgy ").
WSGI allows developers to separate the web framework and web server. You can match the web server and the web framework in a hybrid manner and select a suitable pair. For example, you can run Django, Flask, or Pyramid on Gunicorn, Nginx/uWSGI, or Waitress. The real hybrid matching benefits WSGI's support for both servers and architectures.
The web server must have WSGI interfaces, and all modern Python Web frameworks already have WSGI interfaces. This allows you to collaborate with the web Framework of the server and its characteristics without modifying the code.
WSGI is supported by web servers, while the web framework allows you to select a matching method that suits your needs, however, it also facilitates server and framework developers so that they can focus on their preferred fields and expertise without mutual restraint. Other languages have similar interfaces: java has Servlet APIs and Ruby has Rack.
3. Define the WSGI Interface
The WSGI interface is easy to define. It only requires Web developers to implement a function to respond to HTTP requests. Let's take a look at the simplest Web version of "Hello World !" :
def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return 'Hello World!'
The preceding application () function is an HTTP processing function conforming to the WSGI standard. It receives two parameters:
- Environ: A dict object that contains all HTTP request information;
- Start_response: a function that sends an HTTP response.
The entire application () function does not involve any parsing of HTTP. That is to say, the underlying web Server Parsing and application logic are separated so that developers can concentrate on a field.
The application () function must be called by the WSGI server. There are many servers that comply with WSGI specifications. At this time, the purpose of the web server project is to create a server that is very likely to parse static webpages and parse dynamic webpages.
Implementation Code:
Import time, multiprocessing, socket, OS, reclass MyHttpServer (object): def _ init _ (self): serveSocket = socket. socket (socket. AF_INET, socket. SOCK_STREAM) self. serveSocket = serveSocket self. HTMLPATH = '. /html 'def bind (self, port = 8000): self. serveSocket. bind ('', port) def start (self): self. serveSocket. listen () while True: clientSocket, clientAddr = self. serveSocket. accept () print (clientSocket) multip Rocessing. process (target = self. serveHandler, args = (clientSocket, clientAddr )). start () clientSocket. close () def serveHandler (self, clientSocket, clientAddr): try: recvData = clientSocket. recv (1, 1024 ). decode ('gbk') fileName = re. split (R' + ', recvData. splitlines () [0]) [1] filePath = self. HTMLPATH if fileName. endswith ('. py '): try: pyname = fileName [1:-3] # import pyModule = _ import _ (pyname) env = {} responseBody = PyModule. application (env, self. startResponse) responseLine = self. responseLine responseHeader = self. responseHeader failed t ImportError: responseLine = 'HTTP/1.1 404 not found 'responseHeader = 'server: erbai' + OS. linesep responseHeader + = 'date: % s' % time. ctime () responseBody = '
Html files on the server:
<Html>
<! DOCTYPE html>
Biyeji.png mytime. py file
import timedef application(env,startResponse): status = 'HTTP/1.1 200 OK' responseHeaders = [('Server','bfe/1.0.8.18'),('Date','%s'%time.ctime()),('Content-Type','text/plain')] startResponse(status,responseHeaders) responseBody = str(time.ctime()) return responseBody
Access results:
Homepage
Biye.html
Mytime. py
'''Custom wsgi-compliant framework ''' import timeclass Application (object): def _ init _ (self, urls ): '''route list needs to be obtained during framework initialization ''' self. urls = urls def _ call _ (self, env, startResponse): ''' determines whether a resource is static or dynamic. Set the status code and response header and response body: param env: param startResponse: return: ''' # obtain the file name fileName = env from the request header. get ('path _ info') # judge whether static or dynamic if fileName. startwith ('/static'): fileName = fileName [7:] if '/' = fileName: filePath + = '/index.html' else: filePath + = fileName try: file = None file = open (filePath, 'R', encoding = 'gbk') responseBody = file. read () status = 'HTTP/1.1 200 OK 'responseHeaders = [('server', 'erbai ')] Couldn't FileNotFoundError: status = 'HTTP/1.1 404 Not Found' responseHeaders = [('server', 'erbai')] responseBody = '
If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
626062078. Let's learn Python together!