Custom Web framework (synchronous)

The client sends a request, the server will change sock

The client sends data, the server will change conn

re.match () matches the beginning of the string

Import Socket
 Import SELECT 

class the HttpRequest (Object):
     "" " 
    user package user request information 
    ", "" 
    DEF  the __init__ (Self, Content):
         "" " 

        : param Content: request data sent by the user: the request header and request body 
        " "" 
        self.content = Content 

        self.header_bytes = bytes () 
        self.body_bytes = bytes () 

        self.header_dict = {} 

        self.method = "" 
        self.url = "" 
        Self.protocol = ""

        self.initialize()
        self.initialize_headers()

    def initialize(self):

        temp = self.content.split(b'\r\n\r\n', 1)
        if len(temp) == 1:
            self.header_bytes += temp
        else:
            h, b = temp
            self.header_bytes += h
            self.body_bytes += b

    @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(' ')
            for line in headers:
                kv = line.split(':')
                if len(kv) == 2:
                    k, v = kv
                    self.header_dict[k] = v

# class Future(object):
#     def __init__(self):
#         self.result = None

def main(request):
    return "main"

def index(request):
    return "indexasdfasdfasdf"


routers = [
    ('/main/',main),
    ('/index/',index),
]

def run():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("127.0.0.1", 9999,))
    sock.setblocking(False)
    sock.listen(128)

    inputs = []
    inputs.append(sock)
    while True:
        rlist,wlist,elist = select.select(inputs,[],[],0.05)
        for r in rlist:
            if r == sock:
                """新请求到来"""
                conn,addr = sock.accept()
                conn.setblocking (False) 
                inputs.append (Conn) 
            the else :
                 "" " client to data " "" 
                Data = B "" 
                the while True:
                     the try : 
                        the chunk = r.recv (1024 ) 
                        Data = Data + the chunk
                     the except Exception E AS: 
                        the chunk = None
                     IF  Not the chunk:
                         BREAK 
                # Data processing: request header and request body
                = Request the HttpRequest (Data)
                 # 1. Get URL request header 
                # 2. Central match the outward, gets the specified function 
                # 3 execute the function, the return value acquisition 
                # 4. The return value r.sendall (b'alskdjalksdjf; asfd ') 
                Import Re 
                in Flag = False 
                FUNC = None
                 for route in Routers:
                     IF re.match (route [0], request.url): 
                        in Flag = True 
                        FUNC = route [. 1 ]
                         BREAK 
                IF in Flag:
                    result = func(request)
                    r.sendall(bytes(result,encoding='utf-8'))
                else:
                    r.sendall(b"404")

                inputs.remove(r)
                r.close()

if __name__ == '__main__':
    run()
s6.py

Guess you like

Origin www.cnblogs.com/jintian/p/11445544.html