This article will use 200 lines of code to complete a mini asynchronous non-blocking web framework: Snow. Have a good reference value, follow the small series together to see it
In Python's web framework, Tornado is known for asynchronous non-blocking. This article will use 200 lines of code to complete a mini asynchronous non-blocking web framework: Snow.
First, the source code
This paper is based on the non-blocking socket and IO multiplexing to implement asynchronous non-blocking web framework, which is the internal principle of many asynchronous non-blocking web frameworks.
#!/usr/bin/env python#-*-coding:utf-8-*-import reimport socketimport selectimport timeclass HttpResponse (object): "" " Package response Information "" "Def init (self, content= '): self.content = Content self.headers = {} self.cookies = {} def response (self): Return bytes (self.content, encoding= ' Utf-8 ') class Httpnotfound (HttpResponse): "" "404 Error Message" "" Def Init (self): super ( Httpnotfound, self). init (' 404 Not Found ') class HttpRequest (object): "" "User encapsulates user request Information" "Def init (self, conn): Self.conn = Conn self.header_bytes = bytes () self.header_dict = {} self.body_bytes = bytes () Self.method = "Self.url =" "Self . Protocol = "" Self.initialize () self.initialize_headers () def initialize (self): Header_flag = False while True:try : Received = SELF.CONN.RECV (8096) except Exception as E:received = None if not received:break if header_f Lag:self.body_bytes + = received Continue temp = Received.split (b ' \r\n\r\n ', 1) If Len (temp) = = 1:self.heade R_bytes + = Temp else:h, B = temp Self.header_bytes + = h Self.body_bytes + = b header_flag = True @property def header_str (self): return STR (self.header_bytes, encoding= ' Utf-8 ') def initialize_headers (self): headers = self.header_str.split (' \ r \ n ') first_ line = Headers[0].split (") If Len (first_line) = = 3:self.method, Self.url, Self.protocol = Headers[0].split (") fo R line in headers:kv = Line.split (': ') If Len (kv) = = 2:k, V = kv self.header_dict[k] = Vclass Future (objec T): "" "asynchronous non-blocking mode encapsulates callback function and is ready" "" Def init (Self, callback): Self.callback = Callback Self._ready = False Self.value = None def set_result (self, value=none): Self.value = value Self._ready = True @property def ready: Return Self._re Adyclass timeoutfuture (future): "" "asynchronous non-blocking timeout" "Def init (self, timeout): Super (Timeoutfuture, self). Init (Callback=none) Self.timeout = Timeout Self.start_time = Time.time () @property def Ready (self): Current_time = Time.time () if Current_ Time > Self.start_time + Self.timeout:self._ready = True return self._readyclass Snow (object): "" "Mini web Framework Class" "Def init (self, routes): self. Routes = Routes self.inputs = set () Self.request = None Self.async_request_handler = {} def run (self, host= ' localhost ', port=9999): "" "Event loop:p Aram Host::p Aram Port:: Return:" "" sock = Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind ((host, Port,)) sock.setblocking (False) Sock.listen (+) sock.setblocking (0) Self.inputs.add (s Ock) Try:while true:readable_list, writeable_list, error_list = Select.select (self.inputs, [], self.inputs,0.005) For conn in readable_list:if sock = = conn:client, address = Conn.accept () client.setblocking (False) Self.inputs.add (client) Else:gen = self.process (conn) if Isinstance (Gen, HttpResponse): Conn.sendal L (Gen.response ()) Self.inputs.remove (conn) conn.close () else:yielded = Next (gen) self.async_request _handler[conn] = yielded self.poLling_callback () except Exception as E:pass finally:sock.close () def polling_callback (self): "" Traversal trigger asynchronous non-blocking callback function: R Eturn: "" For Conn in list (Self.async_request_handler.keys ()): yielded = Self.async_request_handler[conn] If not Yi elded.ready:continue If Yielded.callback:ret = Yielded.callback (Self.request, yielded) Conn.sendall (Ret.respo NSE ()) Self.inputs.remove (conn) del Self.async_request_handler[conn] Conn.close () def process (self, conn): "" "Processing Road By the system and the execution function:p Aram Conn:: Return: "" "Self.request = HttpRequest (conn) func = None for the route in Self.routes:if RE.M Atch (Route[0], self.request.url): func = route[1] break if not Func:return Httpnotfound () Else:return func (s Elf.request) snow.py
Second, use
1. Basic use
From snow import snowfrom Snow Import httpresponsedef Index (Request): Return HttpResponse (' OK ') routes = [(R '/index/', Inde x),]app = Snow (routes) App.run (port=8012)
2. Asynchronous non-blocking: timeout
From snow import snowfrom Snow import httpresponsefrom Snow Import timeoutfuturerequest_list = []def async (Request): obj = Timeoutfuture (5) Yield Objdef Home (Request): Return HttpResponse (' home ') routes = [(R '/home/', Home), (R '/async/', async) ,]app = Snow (routes) App.run (port=8012)
3. Asynchronous non-blocking: Waiting
Self-customizing operation based on Wait mode
From snow import snowfrom Snow import httpresponsefrom Snow Import futurerequest_list = []def callback (Request, future): R Eturn HttpResponse (Future.value) def req (request): obj = Future (callback=callback) request_list.append (obj) yield Objdef Stop (Request): obj = request_list[0] del request_list[0] obj.set_result (' Done ') return HttpResponse (' Stop ') Routes = [(R '/req/', req), (R '/stop/', stop),]app = Snow (routes) App.run (port=8012)