1. Browser request Dynamic page process
2.WSGI
Python Web Server Gateway Interface (or simply WSGI, read as "Wizgy").
WSGI allows the developer to separate the selected web framework from the Web server. You can mix and match Web servers and web frameworks to select a suitable pairing. For example, you can run Django, Flask, or Pyramid on Gunicorn or Nginx/uwsgi or waitress. True hybrid matching, thanks to Wsgi supporting both server and architecture.
The Web server must have a WSGI interface, and all modern Python web frameworks have a WSGI interface that allows you to work with the server and feature Web frameworks without modifying the code.
WSGI is supported by a Web server, and the Web framework allows you to choose the pairing that suits you, but it also facilitates server and framework developers so they can focus on their favorite areas and expertise without being diverted. Other languages have similar interfaces: Java has servlet Api,ruby with Rack.
3. Defining the Wsgi interface
Wsgi interface definition is very simple, it only requires the web developer to implement a function, you can respond to HTTP requests. Let's look at one of the simplest web versions of "Hello world!" :
def application (environ, start_response): start_response (' OK ', [(' Content-type ', ' text/html ')] return ' Hello ' world! '
The application () function above is an HTTP processing function that conforms to the WSGI standard, which receives two parameters:
The entire application () function itself does not involve any part of parsing HTTP, that is, separating the parsing part of the underlying Web server from the logic part of the application so that developers can concentrate on a single area.
The application () function must be called by the WSGI server. There are many servers that conform to the WSGI specification. The purpose of our Web server project at this time is to make a server that is most likely to parse static pages and parse dynamic Web pages.
Implementation code:
Import Time,multiprocessing,socket,os,reclass Myhttpserver (object):d EF __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.servesock Et.listen () while true:clientsocket, clientaddr = Self.serveSocket.accept () print (Clientsocket) Multiprocessing. Process (Target=self.servehandler, args= (Clientsocket, clientaddr)). Start () clientsocket.close () def Servehandler (self,clientsocket,clientaddr): Try:recvdata = Clientsocket.recv (1024x768). Decode (' GBK ') FileName = RE.S Plit (R ' + ', Recvdata.splitlines () [0]) [1] FilePath = self. Htmlpathif filename.endswith ('. Py '): try:pyname=filename[1:-3]# import pymodule = __impo rt__ (pyname) env={} responsebody = Pymodule.applicatiOn (env,self.startresponse) Responseline = self.responseline Responseheader = self.re Sponseheaderexcept importerror:responseline = ' http/1.1 404 Not FOUND ' Responsehead er = ' server:ererbai ' + os.linesep responseheader + = ' Date:%s '% time.ctime () resp Onsebody = '
HTML files that exist in the server:
<! DOCTYPE html>
Biyeji.png
mytime.py file
Import timedef Application (env,startresponse): status = ' http/1.1 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:
Home
Biye.html
mytime.py
' Custom WSGI framework ' ' Import Timeclass Application (object):d EF __init__ (Self, URLs): ' ' The framework needs to get a list of routes when it is initialized ' Self.urls = Urlsdef __call__ (self, env, startresponse): "The judge is a static resource or a dynamic resource." Set the status code and response header and response body:p Aram env::p Aram Startresponse:: Return: "# gets the filename from the request header filename = env . Get (' Path_info ') # determine static or dynamic if Filename.startwith ('/static '): filename = filename[7:]if '/' = = FileName: FilePath + = '/index.html ' else:filepath + Filenametry:file = None F ile = open (FilePath, ' R ', encoding= ' GBK ') responsebody = File.read () status = ' http/1.1 200 OK ' responseheaders = [(' Server ', ' Ererbai ')]except filenotfounderror:status = ' http/1.1 40 4 Not Found ' responseheaders = [(' Server ', ' Ererbai ')] responsebody = '
If you encounter any problems in the learning process or want to acquire learning resources, please join the Learning Exchange Group
626062078, we learn python! together.