HTTP Protocol Features
  • 1. Based on TCP/IP

  • 2. Short connection

  • 3. Passive response

  • 4. A stateless

Use Socket to implement a Web service

impotr Scoket def main(): sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind('localhost',8000) sock.listen(5) while True: Data =conn.recv(1024) print(data) # conn. Send (b"HTTP//1.1 20 ok \r\nContent-type:text/html; Charset = UTF-8 \r\n\r\n") conn.send("<h1 style='color:red'>Hello Word</h1>".encode(" utF-8 ")) # close socker connection created with browser conn.close() if__name__=="__main__" main()Copy the code

WSGI

Defines the interface format between a Web App (application) written in Python and a Web Server (Socker server) to decouple the two

Implement a Web service with WSGIREF

Environ: a dict object that contains all HTTP request information;

Start_response: a function that sends an HTTP response.

from wsgiref.simple_server import make_server def run_server(environ,start_response) print('hello',environ) start_response("200 OK",[('Content-type','text/html;charset=utf-8')]) return [bytes('<h2>wsgire implementation web service </h2>',encoding=" UTF-8 ")] s=make_server('localhost',8000,run_server) s.server_forever()Copy the code

The route dispatcher is used to match urls to corresponding functions

def book(environ,start_response): print("book page") start_response("200 ok",[('Content-Type','text/html;charset=utf-8')]) return [bytes('<h2>book page!</h2>',encoding="utf-8")] def cloth(environ,start_response): print("cloth page") start_response("200 ok",[('Content-Type','text/html;charset=utf-8')]) return [bytes('<h2>cloth page</h2>',encoding="utf-8")] def url_dispacher(): Return urls def run_server(environ, start_Response): {'/book':book, '/cloth':cloth,} return urls def run_server(environ,start_response): Print ('hahahaha',environ) url_list=url_dispacher() # request_url=environ. Get ("PATH_INFO") print('request ' url',request_url) if request_url in url_list: func_data=url_list[request_url](environ,start_response) return func_data else: start_response("404",[('Content-Type','text/html;charset=utf-8')]) return [bytes('<h1 style="font-size:50px">404,Page not found!</h1>',encoding="utf-8")] s=make_server('localhost',8000,run_server) s.server_forever()Copy the code