Talking about Web Framework

Keywords: Python socket encoding Django

I. Essence of Web Framework

  • All Web applications are essentially a socket server, and the user's browser is a socket client.

II. Web Framework Function

  • socket sends and receives messages - wsgiref (test), uwsgi (online)

  • Returns different strings according to different paths

  • Return dynamic pages (string substitution) - jinja2

III. Types of Web Framework

  • django

    • Returns different strings according to different paths

    • Return to dynamic page (string substitution)

  • flask

    • Returns different strings according to different paths

  • tornado

    • socket sends and receives messages

    • Returns different strings according to different paths

    • Return to dynamic page (string substitution)

4. Custom web Framework

  • Simple example: socket server

    import socket
    # Create a socket object
    sk = socket.socket()
    # binding IP And port
    sk.bind(('127.0.0.1', 8000))
    # Monitor
    sk.listen(5)
    # Waiting for connection
    while True:
        conn, addr = sk.accept()
        # receive data
        data= conn.recv(1024)
        print(data)
        # Return data
        conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>ok!</h1>')
        # Disconnect
        conn.close()
  • Return different content according to different paths (plain version)

    import socket
    # Create a socket object
    sk = socket.socket()
    # binding IP And port
    sk.bind(('127.0.0.1', 8000))
    # Monitor
    sk.listen(5)
    # Waiting for connection
    while True:
        conn, addr = sk.accept()
        # receive data
        data = conn.recv(1024)
        data = data.decode('utf-8')
        url = data.split()[1]
        conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
        if url == '/index/':
            # Return data
            conn.send(b'<h1>index!</h1>')
        elif url == '/home/':
            conn.send(b'<h1>home!</h1>')
        else:
            conn.send(b'<h1>404 not found!</h1>')
        # Disconnect
        conn.close()
    Ordinary Edition
import socket
# Create a socket object
sk = socket.socket()
# binding IP And port
sk.bind(('127.0.0.1', 8000))
# Monitor
sk.listen(5)
# function
def index(url):
    ret = '<h1>index!</h1>({})'.format(url)
    return ret.encode('utf-8')
def home(url):
    ret = '<h1>home!</h1>({})'.format(url)
    return ret.encode('utf-8')
# Waiting for connection
while True:
    conn, addr = sk.accept()
    # receive data
    data = conn.recv(1024)
    data = data.decode('utf-8')
    url = data.split()[1]
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    if url == '/index/':
        # Return data
        ret = index(url)
    elif url == '/home/':
        ret = home(url)
    else:
        ret = b'<h1>404 not found!</h1>'
    conn.send(ret)
    # Disconnect
    conn.close()
Function version
import socket
# Create a socket object
sk = socket.socket()
# binding IP And port
sk.bind(('127.0.0.1', 8000))
# Monitor
sk.listen(5)
# function
def index(url):
    ret = '<h1>index!</h1>({})'.format(url)
    return ret.encode('utf-8')
def home(url):
    ret = '<h1>home!</h1>({})'.format(url)
    return ret.encode('utf-8')
# Define a list1 Correspondence to the actual function to be executed 
list1 = [
    ('/index/', index),
    ('/home/', home),
]
# Waiting for connection
while True:
    conn, addr = sk.accept()
    # receive data
    data = conn.recv(1024)
    data = data.decode('utf-8')
    url = data.split()[1]
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    func = None
    for i in list1:
        if url == i[0]:
            func = i[1]
            break
    if func:
        ret = func(url)
    else:
        ret = b'<h1>404 not found!</h1>'
    conn.send(ret)
    # Disconnect
    conn.close()
Function Advanced Edition
import socket
# Create a socket object
sk = socket.socket()
# binding IP And port
sk.bind(('127.0.0.1', 8000))
# Monitor
sk.listen(5)
# function
def index(url):
    with open('index.html','rb') as f:
        ret = f.read()
    return ret
def home(url):
    ret = '<h1>home!</h1>({})'.format(url)
    return ret.encode('utf-8')
# Define a list1 Correspondence to the actual function to be executed
list1 = [
    ('/index/', index),
    ('/home/', home),
]
# Waiting for connection
while True:
    conn, addr = sk.accept()
    # receive data
    data = conn.recv(1024)
    data = data.decode('utf-8')
    url = data.split()[1]
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    func = None
    for i in list1:
        if url == i[0]:
            func = i[1]
            break
    if func:
        ret = func(url)
    else:
        ret = b'<h1>404 not found!</h1>'
    conn.send(ret)
    # Disconnect
    conn.close()
Return to html page
import socket
import time
# Create a socket object
sk = socket.socket()
# binding IP And port
sk.bind(('127.0.0.1', 8000))
# Monitor
sk.listen(5)
# function
def index(url):
    with open('index.html', 'rb') as f:
        ret = f.read()
    return ret
def home(url):
    ret = '<h1>home!</h1>({})'.format(url)
    return ret.encode('utf-8')
def timer(url):
    now = time.strftime('%H:%M:%S')
    with open('time.html','r',encoding='utf-8') as f:
        data = f.read()
    data = data.replace('xxtimexx',now)
​
    return data.encode('utf-8')
# Define a list1 Correspondence to the actual function to be executed
list1 = [
    ('/index/', index),
    ('/home/', home),
    ('/time/', timer),
]
# Waiting for connection
while True:
    conn, addr = sk.accept()
    # receive data
    data = conn.recv(1024)
    data = data.decode('utf-8')
    url = data.split()[1]
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    func = None
    for i in list1:
        if url == i[0]:
            func = i[1]
            break
    if func:
        ret = func(url)
    else:
        ret = b'<h1>404 not found!</h1>'
    conn.send(ret)
    # Disconnect
    conn.close()
//Supplement: time.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>The current time is:@@time@@</h1>
</body>
</html>
Return to dynamic page

5. wsgiref

Six, jinja2

  1. Template rendering off-the-shelf tool: jinja2

  2. Example:

    from wsgiref.simple_server import make_server  
    from jinja2 import Template    
      
    def index(url):  
        # read HTML Document content  
        with open("index2.html", "r", encoding="utf8") as f:  
            data = f.read()  
            template = Template(data)   # Generate template files 
            ret = template.render({'name': 'alex', 'hobby_list': ['smoking', 'drink', 'Hot head']})   # Fill data into templates  
        return bytes(ret, encoding="utf8")  
      
    def home(url):  
        with open("home.html", "r", encoding="utf8") as f:  
            s = f.read()  
        return bytes(s, encoding="utf8")  
      
    # Define a url Correspondence to the actual function to be executed  
    list1 = [  
        ("/index/", index),  
        ("/home/", home),  
    ]   
      
    def run_server(environ, start_response):  
        start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # Set up HTTP Response status wharf and wharf information  
        url = environ['PATH_INFO']  # Input to the user url  
        func = None  
        for i in list1:  
            if i[0] == url:  
                func = i[1]  
                break  
        if func:  
            response = func(url)  
        else:  
            response = b"404 not found!"  
        return [response, ]  
      
    if __name__ == '__main__':  
        httpd = make_server('127.0.0.1', 8090, run_server)  
        print("I'm waiting for you at 8090....")  
        httpd.serve_forever() 
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Title</title>
    </head>
    <body>
        <h1>Full name:{{name}}</h1>
        <h1>Hobbies:</h1>
        <ul>
            {% for hobby in hobby_list %}
                <li>{{hobby}}</li>
            {% endfor %}
        </ul>
    </body>
    </html>
    index2.html

Posted by cptnwinky on Mon, 07 Oct 2019 23:20:58 -0700