Chapter 12 Django Framework
12.1 Server applications and Applications
The server program is responsible for encapsulating the socket server and sorting out all kinds of data requested when the request arrives. The application is responsible for specific logical processing. In order to facilitate the development of applications, there are many Web frameworks, such as Django, Flask, web.py and so on. Different frameworks have different ways of development, but in any case, the developed applications must cooperate with server programs in order to provide services for users.
WSGI (Web Server Gateway Interface) is a specification, which defines the interface format between web application program and web server program written in Python, and realizes 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 Python standard library is called wsgiref. The Django development environment uses this module as the server.
12.11 Replace socket server with wsgiref
import time from wsgiref.simple_server import make_server def home(url): # Encapsulate the parts returning different contents into functions s = "this is {} page!".format(url) return bytes(s, encoding="utf8") def index(url): return b'<h1>index page</h1>' def user(url): # Different users get pages that display different times c_time = str(time.time()) with open("user.html", "r") as f: data_s = f.read() data_s = data_s.replace("@@xx@@", c_time) return bytes(data_s, encoding="utf8") url2func = [ # url Correspondence to the actual function to be executed ("/index/", index), ("/home/", home), ("/user/", user),] def run_server(environ, start_response):# according to wsgiref Requirements define a run_server function 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 url2func: if url == i[0]: func = i[1] # Get the function to be executed break if func: msg = func(url) # Execute the corresponding function else: msg = b'<h1>404</h1>' # If the function to be executed is not found, 404 is returned. return [msg, ] # Send message to client if __name__ == '__main__': httpd = make_server('127.0.0.1', 8090, run_server) print("I'm waiting for you at 8090....") httpd.serve_forever()
12.12 HTML template rendering tool jinja2
user.html:
<body> <table border="1"> <thead> <tr> <th>id</th> <th>Full name</th> <th>hobby</th> </tr> </thead> <tbody> {% for user in user_list %} <tr> <td>{{user.id}}</td> <td>{{user.name}}</td> <td>{{user.hobby}}</td> </tr> {% endfor %} </tbody> </table> </body>
Replace data in HTML with jinjia2:
Use pymysql module to query database to get data, and use jinjia2 to replace data in HTML
The principle of template is string substitution. As long as we follow jinja2's grammar rules in HTML pages, it will be replaced in accordance with the specified grammar to achieve dynamic content return.
import time from wsgiref.simple_server import make_server from jinja2 import Template import pymysql def user(url): conn = pymysql.connect( # Get all the user information from the database. host='127.0.0.1', port=3306, user='root', password='123', database='db6', charset='utf8' ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('select * from user') ret = cursor.fetchall() #print(ret) with open("user.html", "r", encoding="utf8") as f: data_s = f.read() template = Template(data_s) # Generate an instance of a template file msg = template.render({"user_list": ret}) # Fill the data in the template return bytes(msg, encoding="utf8") url2func = [ # url Correspondence to the function to be executed ("/index/", index), ("/home/", home), ("/user/", user),] def run_server(environ, start_response): # according to wsgiref Requirements define a run_server function 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 url2func: if url == i[0]: func = i[1] # Get the function to be executed break if func: msg = func(url) # Execute the corresponding function else: msg = b'<h1>404</h1>' # If the function to be executed is not found, 404 is returned. return [msg, ] # Send message to client if __name__ == '__main__': httpd = make_server('127.0.0.1', 8090, run_server) print("I'm waiting for you at 8090....") httpd.serve_forever()
12.2 Django Basic Essential Three-piece Set
Create a Django project called "mysite" with commands
django-admin startproject mysite
Django directory:
mysite/ ├── manage.py # Management documents └── mysite # Project catalogue ├── __init__.py ├── settings.py # To configure ├── urls.py # Route --> URL The Correspondence of Sum Function └── wsgi.py # runserver The command is used wsgiref Modules are simple web server
Run the Django project with commands
python3 manage.py runserver 127.0.0.1:8000 #Default port 8000
Template file configuration: settings
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "template")], # template Folder location 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
Static file configuration: settings
STATIC_URL = '/static/' # HTML Static folder prefix used STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), # Static File Storage Location ]
12.21 HttpResponse
A string parameter is passed in and returned to the browser
from django.conf.urls import url from django.contrib import admin from django.shortcuts import HttpResponse, render, redirect def index(request): #All request-related data is encapsulated request In this parameter # Business logic code return HttpResponse("This is index Page!")
12.22 render
In addition to the request parameter, it accepts a template file to be rendered and a dictionary parameter to hold specific data, fills the data into the template file, and finally returns the results to the browser (similar to jinja2 used above).
def login(request): # Find it by yourself HTML file # with open("templates/login.html", "r", encoding="utf8") as f: # data = f.read() # return HttpResponse(data) # Django Look for login.html File, read out content, return to browser return render(request, "login.html", {"name": "alex", "hobby": ["Hot head", "Bubble bar"]})
12.23 redirect
Accept a URL parameter to indicate a jump to the specified URL
def index(request): # Business logic code return redirect("/home/")
12.24 Set the corresponding relationship between the URL and the function
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', home), url(r'^index/', index), url(r'^login/', login), ]