Python's Web server

Source: Internet
Author: User

1. Browser request dynamic page procedure 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(‘200 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:

    • Environ: A Dict object that contains all the HTTP request information;
    • Start_response: A function that sends an HTTP response.

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,reClassMyhttpserver(object):Def__init__(self): Servesocket = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Self.servesocket = Servesocket self. Htmlpath ='./html 'DefBind(self,port=8000): Self.serveSocket.bind ((", port))DefStart(self): Self.serveSocket.listen ()WhileTrue:clientsocket, clientaddr = Self.serveSocket.accept () print (clientsocket) multiprocessing. Process (Target=self.servehandler, args= (Clientsocket, clientaddr)). Start () Clientsocket.close ()DefServehandler(SELF,CLIENTSOCKET,CLIENTADDR):Try:recvdata = CLIENTSOCKET.RECV ((decode).' GBK ') FileName = Re.split (R ' + ', recvdata.splitlines () [0]) [1] FilePath = self. HtmlpathIf Filename.endswith ('. Py '):try:pyname=filename[1:-3]# import Pymodule = __import__ (pyname) env={} responsebody = Pymodule.application (env,self.startresponse) responseLine = self . responseline Responseheader = Self.responseheaderexcept Importerror:responseline =' http/1.1 404 Not FOUND ' Responseheader =' Server:ererbai ' + os.linesep Responseheader + =' Date:%s '% time.ctime () Responsebody =' ElseIf'/' = = Filename:filepath + ='/index.html 'Else:filepath + = FileNameTry:file =None file =open (FilePath,' R ', encoding=' GBK ') responsebody = File.read () Responseline =' http/1.1 OK ' Responseheader =' Server:ererbai ' + os.linesep Responseheader + =' date:%s '% time.ctime ()except Filenotfounderror:responseline =' http/1.1 404 Not FOUND ' Responseheader =' Server:ererbai ' + os.linesep Responseheader + =' date:%s '% time.ctime () Responsebody =' I'm sorry, I can't find what you're looking for in the server. 'Finallyif (file!=None)and (Not file.closed): File.close ()Except ExceptionAs Ex:responseline =' http/1.1 ERROR ' Responseheader =' Server:ererbai ' + os.linesep Responseheader + =' Date:%s '% time.ctime () Responsebody =' The server is in maintenance, please try again later. %s '%exFinally:sendata = responseline + os.linesep + responseheader + os.linesep + os.linesep + responsebody print (senData) SenD ATA = Sendata.encode (' GBK ') clientsocket.send (sendata) if (clientsocket!=None) and (not clientsocket._closed): Clientsocket.close () def startresponse(self,status,responseheaders): Self.responseline = Status Self.responseheader = ' for k,v in responseheaders:kv = k + ': ' + V + os.linesep Self.responseheader + = kvif __name__ = = ' __main__ ': Server = Myhttpserver () server.bind (8000) Server.start ()  

HTML files that exist in the server:

    • Index.html
<html><head>    <title>首页-毕业季</title> <meta http-equiv=Content-Type content="text/html;charset=gbk"></head><body>我们仍需共生命的慷慨与繁华相爱,即使岁月以刻薄和荒芜相欺。</body></html>
    • Biye.html
<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="GBK" ><Title> Graduation Season</Title></Head><body>! [] (Http://localhost:51017/day18/html/biyeji.png)<Br> thought June, but it was normal.<br> when he really went through the graduation <br> Just know occasionally see June graduation season and other words revealed in the various want to relive but dare not mention memories <br> graduated <br> that summer, my graduation season, my youth <br> June <br> someone laughed and said relief, someone cried and said no <br> that year, < br> you said to me hello <br> unconsciously <br> became <br> goodbye. </body></ HTML>             

biyeji.pngmytime.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:
Home
Biye.html
mytime.py
"Custom-WSGI framework"Import timeClassApplication(object):Def__init__(Self, URLs):"The framework needs to get the route list when it initializes" Self.urls = URLsDef__call__(Self, env, startresponse):"' Determine whether it is a static or 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 dynamicIf Filename.startwith ('/static '): FileName = filename[7:]If'/' = = Filename:filepath + ='/index.html 'Else:filepath + = FileNameTry:file =None file = open (FilePath,' R ', encoding=' GBK ') responsebody = File.read () status =' http/1.1 OK ' responseheaders = [(' Server ',' Ererbai ')]except filenotfounderror:status =' http/1.1 404 Not Found ' responseheaders = [(' Server ',' Ererbai ')] Responsebody =' Finally:startresponse (status, Responseheaders)if (File! =None)and (Not file.closed): File.close ()Else:ishas =False# Indicates whether the requested name is in the URLs, True: exists, False: does not existFor URL, funcIn Self.urls:If url = = Filename:responsebody = Func (env, startresponse) Ishas =TrueBreakif Ishas = =False:status =' http/1.1 404 Not Found ' responseheaders = [(' Server ',' Ererbai ')] Responsebody =' Return responsebodyDefMyTime(env, startresponse): status =' http/1.1 OK ' responseheaders = [(' Server ', ' time ')] startresponse (status, Responseheaders) Responsebody = str (time.ctime ()) return responsebodydef mynews(env, startresponse): status = ' http/ 1.1 OK ' responseheaders = [(' Server ', ' News ')] startresponse (status, responseheaders) responsebody = str (
                                                                             
                                                                               ' XX News ') 
                                                                              return responsebody' route list ' urls = [('/mytime ', MyTime), ('/mynews ', mynews)] Application = Application (URLs)    
                                                                                      

You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
626062078, we learn python! together.

Python's Web server

Related Article

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.