Introduction to Django Framework, wsgiref and jinja2 Modules

Posted by Bailz on Tue, 11 Jun 2019 20:59:13 +0200

Catalog

Brief introduction to framework

  • Django is a web development framework for developing web applications. The essence of Django is web framework + socket server.

  • MVC Framework and MTV Framework
MVC, whose full name is Model View Controller, is a software architecture pattern in software engineering. It divides software system into three basic parts:
Model, View and Controller have the advantages of low coupling, high reusability and low life cycle cost.

The design pattern of Django framework draws on the idea of MVC framework and is also divided into three parts to reduce the coupling between various parts.
The difference of Django framework is that it is divided into three parts: Model, Template and View, that is, MTV framework.
  • Django's MTV mode
Model: Objects responsible for business objects and databases (ORM)

       Template: Responsible for presenting pages to users

       View: Responsible for business logic and call Model and Template when appropriate
        
In addition, Django has a urls distributor that distributes page requests from one URL to different view s for processing.
view calls the corresponding Model and Template
  • WSGI (Web Server Gateway Interface Specification)

Server programs need different support for different frameworks. This chaotic situation is not good for servers or frameworks.
For servers, different frameworks need to be supported. For frameworks, only servers that support them can be used by applications developed.

At this time, standardization becomes particularly important. We can set up a standard, as long as the server program supports this standard, the framework also supports this standard.
Then they can cooperate. Once the criteria are established, each party will implement them. In this way, servers can support more standards-supporting frameworks.
Frameworks can also use more standard-enabled servers.

WSGI (Web Server Gateway Interface) is a specification that defines web applications written in Python
 The interface format between web server program and web server program can realize the decoupling between web application program and web server program.

The commonly used WSGI servers are uWSGI and Gunicorn. The independent WSGI server provided by the Python standard library is called wsgiref.
Django development environment uses this module as server

wsgiref module

  • The independent WSGI server provided by Python standard library is called wsgiref.

  • uWSGI is commonly used in online servers

#The wsgiref module replaces the socket server part of our own web framework:

    """  
    //Return different content according to different paths in the URL -- Function Advanced Edition  
    //Return to the HTML page  
    //Make Web pages dynamic  
    wsgiref Modular version  
    """   
         
    from wsgiref.simple_server import make_server   
         
         
    # Encapsulate the parts returning different contents into functions   
    def index(url):   
        # Read the contents of the index.html page   
        with open("index.html", "r", encoding="utf8") as f:   
            s = f.read()   
        # Returns byte data   
        return bytes(s, encoding="utf8")   
         
         
    def home(url):   
        with open("home.html", "r", encoding="utf8") as f:   
            s = f.read()   
        return bytes(s, encoding="utf8")   
         
         
    def timer(url):   
        import time   
        with open("time.html", "r", encoding="utf8") as f:   
            s = f.read()   
            s = s.replace('@@time@@', time.strftime("%Y-%m-%d %H:%M:%S"))   
        return bytes(s, encoding="utf8")   
         
         
    # Define the corresponding relationship between a url and the actual function to be executed   
    list1 = [   
        ("/index/", index),   
        ("/home/", home),   
        ("/time/", timer),   
    ]   
         
         
    def run_server(environ, start_response):   
        start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # Setting the status code and terminal information for HTTP response   
        url = environ['PATH_INFO']  # Fetch the url entered by the user   
        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) 
        httpd.serve_forever()  
  • html code
<!--index Page a file with a piece of code,I've written it together here.-->
<!DOCTYPE html>
<html lang="en">
<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>index</title>
</head>
<body>
<div>This is index page</div>
</body>
</html>

<!--home Page a file with a piece of code,I've written it together here.-->
<!DOCTYPE html>
<html lang="en">
<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>home</title>
</head>
<body>
<div>This is home page</div>
</body>
</html>

<!--time Page a file with a piece of code,I've written it together here.-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>time</title>
</head>
<body>
    <div>@@time@@</div>
</body>
</html>
  • results of enforcement

jinja2 module

#The above code implements a simple dynamic, I can query data from the database, and then replace the corresponding content in my html.
//Then send it to browser to finish rendering. This process is equivalent to HTML template rendering data. Essentially the use of HTML content
//Some special symbols are used to replace the data to be displayed. The special symbols I use here are defined by me. In fact, template rendering has an off-the-shelf tool: jinja2

#Command line installation of jinja2 module  
      pip install jinja2
    
    
# Rendering index 2.html file with jinja2: code  
from wsgiref.simple_server import make_server  
from jinja2 import Template  
  
def index(url):  
    # Read HTML file 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 the corresponding relationship between a url and 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'), ])  # Setting the status code and terminal information for HTTP response  
    url = environ['PATH_INFO']  # Fetch the url entered by the user  
    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)  
    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>            <!--Provisional Writing{{}}-->
    <h1>Hobbies:</h1>
    <ul>
        {% for hobby in hobby_list %}  <!--Provisional Writing{% %}Hand python Distinguish-->
        <li>{{hobby}}</li>
        {% endfor %}                 <!--Provisional Writing{% endfor %}Hand python Identify the end cycle--> 
    </ul>
</body>
</html>
  • results of enforcement

  • Use the database to query data to fill pages
#Connect to the database using pymysql:
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="xxx", db="xxx", charset="utf8")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select name, age, department_id from userinfo")
user_list = cursor.fetchall()
cursor.close()
conn.close()

#Create a user table for the test:
CREATE TABLE user(
  id int auto_increment PRIMARY KEY,
  name CHAR(10) NOT NULL,
  hobby CHAR(20) NOT NULL
)engine=innodb DEFAULT charset=UTF8;

#The principle of templates is string substitution. We just write them in HTML pages following the jinja2 grammar rules.
//Its interior will be replaced according to the specified grammar, so as to achieve dynamic content return.
  • A brief look at the python web Framework

  • Functions of web framework implementation

# django framework, tornado (asynchronous non-blocking lightweight framework), flask framework

Functions implemented by django framework

Functions implemented by tornado framework

flask Framework Implements Functions of Figure 2

Topics: PHP encoding Django Python Web Server