Web framework essence ##


Web System Concepts

1. Http, stateless, short connection 2. Browser (Socket client), website (Socket server)Copy the code

Web Framework nature

import socket  
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, Seven")  
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8000))
    sock.listen(5)  
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()  
if __name__ == '__main__':
    main()
Copy the code

Customize the Web framework

A. Socket server b. Return different content routing systems based on different URLS: URL -> function C. The string is returned to the user by the template engine rendering: THE HTML acts as a template (special character) to create arbitrary data strings itselfCopy the code
  • Static site processing:
Import socket def f1(request): """ Param request: all information requested by the user :return: """ f = open('index.fsw','rb') data = f.read() f.close() return data def f2(request): f = open('aricle.tpl','rb') data = f.read() f.close() return data routers = [ ('/xxx', f1), ('/ooo', f2), ] def run(): Socket = sock. socket() sock.bind(('127.0.0.1',8080)) sock.listen(5) while True: Data = conn.recv(8096) data = STR (data,encoding=' utF-8 ') headers,bodys = data.split('\r\n\r\n') temp_list = headers.split('\r\n') method,url,protocal = temp_list[0].split(' ') Conn. send(b"HTTP/1.1 200 OK\r\n\r\n") func_name = None for item in routers: if item[0] == URL func_name = item[1] break if func_name: response = func_name(data) else: response = b"404" conn.send(response) conn.close() if __name__ == '__main__': run()Copy the code
  • Dynamic site handling method I (manual replacement template engine) :
import socket def f3(request): Conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123',db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('select Id,username,password from userinfo') user_list = cursor.fetchall() cursor.close() conn.close() for row in user_list: tp = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(row['id'],row['username'],row['password']) content_list.append(tp) F = open('userlist.html','r',encoding=' utF-8 ') template = f.read() f.close() data = template.replace('@@sdfsdffd@@', content) return bytes(data, Encoding =' UTF-8 ') # phut = [('/userlist.htm', F3),] def run(): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock. Bind (('127.0.0.1',8080)) sock. Listen (5) while True: Data = conn.recv(8096) data = STR (data,encoding=' utF-8 ') headers,bodys = data.split('\r\n\r\n') temp_list = headers.split('\r\n') method,url,protocal = temp_list[0].split(' ') Conn. send(b"HTTP/1.1 200 OK\r\n\r\n") func_name = None for item in routers: if item[0] == URL func_name = item[1] break if func_name: response = func_name(data) else: response = b"404" conn.send(response) conn.close() if __name__ == '__main__': run()Copy the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <table border="1"> <thead> < tr > < th > ID < / th > < th > user name < / th > < th > email < / th > < / tr > < thead > < tbody > @ @ SDFSDFFD @ @ < / tbody > < / table > < / body > < / HTML >Copy the code

Dynamic Website 2 (replaced with Jinjia2 template engine)

import socket def f4(request): Conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,username,password from userinfo") user_list = cursor.fetchall() cursor.close() conn.close() f = open('hostlist.html','r',encoding='utf-8') data From jinja2 import Template Template = Template(data) data = Template. render(XXXXX =user_list, user='dsafsdfsdf') return data. Encode (' UTF-8 ') ] def run(): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock. Bind (('127.0.0.1',8080)) sock. Listen (5) while True: Data = conn.recv(8096) data = STR (data,encoding=' utF-8 ') headers,bodys = data.split('\r\n\r\n') temp_list = headers.split('\r\n') method,url,protocal = temp_list[0].split(' ') Conn. send(b"HTTP/1.1 200 OK\r\n\r\n") func_name = None for item in routers: if item[0] == URL func_name = item[1] break if func_name: response = func_name(data) else: response = b"404" conn.send(response) conn.close() if __name__ == '__main__': run()Copy the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <table border="1"> <thead> < tr > < th > ID < / th > < th > user name < / th > < th > email < / th > < / tr > < thead > < tbody > {% for the row in XXXXX %} < tr > < td > {{row. ID}} < / td > <td>{{row.username}}</td> <td>{{row.password}}</td> </tr> {% endfor %} </tbody> </table> {{user}} </body> </html>Copy the code

Basics of the Django framework


Frame type

- a, b, c - > Tornado - [a] by a third party, b, c - > wsgiref - > Django - [a] by a third party, b, [third party c] -- > flask,Copy the code

Pre-configuration of Django project

Django-admin startproject mysite django-admin startproject mysite Waiting for the user to send a request python manage.py runServer 127.0.0.1:8080Copy the code
Django configuration file: settings.py...... DIRS ': [OS. Path. Join (BASE_DIR,' template ')],...Copy the code
Mysql database: DATABASES = {'default': {'ENGINE': 'django.db.backends. Mysql ', 'NAME':'dbname', 'USER': 'root', 'PASSWORD': 'xxx', 'HOST': '', 'PORT': }} # note: # Since Django uses the MySQLdb module to connect to MySQL internally, python3 does not have this module. So use pymysql instead of # import pymysql pymysql.install_as_mysqldb () in the __init__.py file of the configuration with the same name as projectCopy the code
Static directory STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)Copy the code
Additional configuration (cross-site request camouflage CRSF) : MIDDLEWARE = [... # 'django. MIDDLEWARE. CSRF. CsrfViewMiddleware',...]Copy the code

Project case

  • Web request
# urls.py urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^index/',index), ] def index(request): # return HttpResponse('Index') return render(request, 'index.html',{ 'name': 'Tom', 'users' : ['' ', 'li'], 'user_dict: {' k1' : 'v1', 'k2: "v2"}, 'user_list_dict':[ {'id':1,'name':'tom','email':'[email protected]'}, {'id':1,'name':'tom','email':'[email protected]'}, {'id':1,'name':'tom','email':'[email protected]'}, {'id':1,'name':'tom','email':'[email protected]'}, ] })Copy the code
# template/index <p>{{ name }}</p> <p>{{ users.0 }}</p> <p>{{ users.1 }}</p> <p>{{ user_dict.k1 }}</p> <p>{{ User_dict. K2}} < / p > < h3 > cycle < / h3 > < ul > {% for the item in the users %} < li > {{item}} < / li > {% endfor %} < / ul > < h3 > cycle < / h3 > < table border="1"> {% for row in user_list_dict %} <tr> <td>{{ row.id }}</td> <td>{{ row.name }}</td> <td>{{ row.email }}</td> < td > < a > edit < / a > | < a href = "/ del /? Nid = {{row. Id}}" > delete < / a > < / td > < / tr > {% endfor %} < / table >Copy the code
  • Website login
# urls from django.conf.urls import url from django.contrib import admin from django.shortcuts import HttpResponse,render,redirect urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^login/',login), ] def login(request): "" return param request: return param request: return param request: return param request: return HttpResponse('<input type="text" />') # return HttpResponse('login. HTML ') # return HttpResponse('login. HTML ') If request.method == "GET": print(request.get) print(request.get) return render(request,'login.html') else: Get ('user') p = request.post. get(' PWD ') if u == 'root' and p == '123': Return redirect('http://www.oldboyedu.com') return redirect('/index/') # redirect else: Render (request,'login.html',{' MSG ': 'username')Copy the code
# template <form method="POST" action="/login/"> <input type="text" name="user" /> <input type="password" name="pwd" /> < input type = "submit" value = "login" / > {{MSG}} < / form >Copy the code

Django Student Management System


Database design structure

Class \ Student \ teacher (class table) : id name Class ID (FK) 1 Linfeng 2 Lindog 3 Yuantian (class table) : Id name class ID (FK) 1 Linfeng 2 Lindog 3 Yuantian (class table) : Id Teacher ID Class ID 1 1 1 2 1 2 3 2 2Copy the code

Class management module

  • Check (master inheritance)
# urls

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'classes/', views.classes),
   ]
Copy the code
# view from django.shortcuts import render,redirect import pymysql def classes(request): Conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123', db='s4db65', Charset = 'utf8) cursor = conn. Cursor (cursor = pymysql. Your cursors. DictCursor) # set the query results to dictionary format cursor. Execute (" select id, Title from class") class_list = cursor.fetchall() # render(request, 'classes.html',{'class_list':class_list})Copy the code
<h1> <div> <a href="/add_class/"> Add </a> < / div > < table > < thead > < tr > < th > ID < / th > < th > class name < / th > < th > action < / th > < / tr > < thead > < tbody > {% for the row in class_list %} < tr > < td > {{row. Id}} < / td > < td > {{row. The title}} < / td > < td > < a href = "" > edit < / a > | < a href =" "> delete < / a > < / td > < / tr > {% endfor %} </tbody> </table> {% endbloc %}Copy the code
  • increase
# urls

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^add_class/', views.add_class),
]

Copy the code
# view def add_class(request): if request.method == 'GET': return render(request,'add_class.html') else: print(request.POST) v = request.POST.get('title') conn = = '127.0.0.1' pymysql. Connect (host, port = 3306, user = 'root', passwd = '123', the db = 's4db65' charset = 'utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('insert into class(title) value(%s)', [v,]) conn.mit () # commit transaction cursor.close() conn.close() return redirect('/classes/')Copy the code
<form method="post" action="/add_class/"> <p> <input type="text" name="title" /></p>Copy the code
  • delete
# urls

urlpatterns = [
      url(r'^del_class/', views.del_class),
  ]

Copy the code
# view def del_class(request): GET ('nid') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='s4db65', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('delete from class where id=%s',[nid,]) conn.commit() cursor.close() conn.close() return redirect('/classes/')Copy the code
  • change
# urls

urlpatterns = [
    url(r'^edit_class/', views.edit_class),
]
Copy the code
# view def edit_class(request): if request.method == 'GET': GET ('nid') conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd =' 123', db='s4db65',charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('select id, title from class where id=%s', [nid,]) result = cursor.fetchone() cursor.close() conn.close() print(result) return render(request,'edit_class.html',{'result':result}) else: nid = request.GET.get('nid') title = request.POST.get('title') print(nid, (the title) conn = pymysql. Connect host = '127.0.0.1', the port = 3306, user = 'root', passwd = '123', the db = 's4db65', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('update class set title=%s where id=%s',[title,nid,]) conn.commit() cursor.close() conn.close() return redirect('/classes/')Copy the code
  • Modal dialog box to achieve the function of adding classes
# HTML <a onclick="showModal()"> dialog box adds </a> <div ID ="shadow" class="shadow hide"></div> <div ID ="modal" class="model Hide "> < p > < input type =" text "id =" title "> < / p > < input type =" button "value =" submit "onclick =" AjaxSend () "/ > < span id =" "> < / span > </div> </div>Copy the code
# css

.hide {
    display: none;
}
.shadow {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
    z-index: 999;
}
.model {
    z-index: 1000;
    position: fixed;
    height: 300px;
    width: 400px;
    background: white;
    left: 50%;
    top: 50%;
    margin-left: -200px;
    margin-top: -150px;
}
Copy the code
# js function showModal() { document.getElementById('shadow').classList.remove('hide') document.getElementById('modal').classList.remove('hide') } function cancleModal() { document.getElementById('shadow').classList.add('hide'); document.getElementById('modal').classList.add('hide'); } function AjaxSend() { $.ajax({ url: '/modal_add_class/', type: 'POST', data: {'title': $('#title').val()}, success: function (data) { console.log(data); if (data == 'ok') { location.href = '/classes'; } else { $('errormsg').text(data); }}})}Copy the code
# urls

urlpatterns = [url(r'^modal_add_class/', views.modal_add_class]
Copy the code
Def modify(SQL,args): def modify(SQL,args): Conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='s4db65', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql,args) conn.commit() cursor.close() conn.close() ---------- def modal_add_class(request): title = request.POST.get('title') if len(title) > 0: sqlheper.modify('insert into class (title) value(%s)',[title,]) return HttpResponse('ok') else: Return HttpResponse(' Class title cannot be empty ')Copy the code

Student Management module

  • check
# urls

url(r'^students/',views.students),
Copy the code
# views

def students(request):
    conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db='s4db65',charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute('select student.id,student.name,class.title from student left JOIN class on student.class_id = class.id')
    student_list = cursor.fetchall()
    cursor.close()
    conn.close()
    print('结果:',student_list)
    return render(request,'students.html',{'student_list':student_list})
Copy the code
# HTML < h1 > student list < / h1 > < div > < a href = "/ add_student/" > add < / a > < / div > < table > < thead > < tr > < th > ID < / th > < th > student's name < / th > The < th > < / th > belongs to class < th > action < / th > < / tr > < thead > < tbody > {% for the row in student_list %} < tr > < td > {{row. Id}} < / td > < td > {{ Row. The name}} < / td > < td > {{row. The title}} < / td > < td > < a href = "" > edit < / a > < a > delete < / a > < / td > < / tr > {% endfor %} < / tbody > < / table >Copy the code
  • increase
# urls

url(r'^add_student/',views.add_student)
Copy the code
# views def add_student(request): if request.method == 'GET': Conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db=' s4DB65 ',charset='utf8') cursor =  conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('select id,title from class') class_list = cursor.fetchall() cursor.close() conn.close() return render(request,'add_student.html',{'class_list':class_list}) else: Conn = request.post.get ('class_id') conn = request.post.get ('class_id') conn = = '127.0.0.1' pymysql. Connect (host, port = 3306, user = 'root', passwd = '123', the db = 's4db65' charset = 'utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute('insert into student(name,class_id)values(%s,%s)',[name,class_id,]) conn.commit() cursor.close() conn.close() return redirect('/students/')Copy the code
<form method="post" action="/add_student/"> <p> Student name <input type="text" name="name"> </p> <p> Class <select name='class_id'> {% for row in class_list %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} < / select > < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
  • change
# urls

url(r'^edit_student/',views.edit_student),
Copy the code
# views from utils import sqlheper def edit_student(request): if request.method == "GET": nid = request.GET.get('nid') class_list = sqlheper.get_list("select id,title from class",[]) current_student_info = Sqlheper. get_one('select id,name,class_id from student where id=%s',[nid,]) print(' ',class_list,current_student_info,nid) return render(request,'edit_student.html',{'class_list': class_list,'current_student_info':current_student_info}) else: nid = request.GET.get('nid') name = request.POST.get('name') class_id = request.POST.get('class_id') sqlheper.modify('update student set name=%s,class_id=%s where id=%s',[name,class_id,nid,]) return redirect('/students/')Copy the code
<form method="post" action="/edit_student/? Nid ={{current_student_info.id}}">< p> Student name <input type="text" name="name" value="{{current_student_info.name}}"></p> <p> Class < SELECT name="class_id"> {% for row in class_list %} {% if row.id == current_student_info.class_id %} <option selected="selected" value="{{ row.id }}">{{ row.title }}</option> {% else %} <option value="{{ row.id }}">{{ row.title Endif}} < option > {% %} {% endfor %} < / select > < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
  • The modal dialog box is added
# HTML <div class="shadow hide" id="shadow"></div> <div class=" add-modal hide" ID ="addModal"> <input id=" placeholder "type=" placeholder "name =" placeholder" /></p> <p>  <select id="addClassId" name="classId"> {% for row in class_list %} <option value="{{ row.id }}">{{ Row. title}}</option> {% endfor %} </select> </p> <p> < INPUT ID ="btnAdd" type="button" value=" add "/> <input <span id="addError" style="color: red"></span> </div>Copy the code
# css

.shadow{
    position: fixed;
    top: 0;
    bottom:0;
    left:0;
    right: 0;
    background-color: black;
    opacity: 0.5;
    z-index: 999;
}
.add-Modal{
    position: fixed;
    top:50%;
    left:50%;
    width: 400px;
    height: 300px;
    z-index: 1000;
    background-color: white;
    margin-left: -200px;
    margin-top: -200px;
}
.hide{
    display: none;
}
Copy the code
# js $(function(){ $('#addModal_window').click(function(){ $('#shadow,#addModal').removeClass('hide'); }); $('#btnCancle').click(function(){ $('#shadow,#addModal').addClass('hide'); }); $('#btnAdd').click(function () { $.ajax({ url: '/modal_add_student/', type: 'POST', data:{'name':$('#addName').val(),'class_id':$('#addClassId').val()}, success:function (arg) { arg = JSON.parse(arg); if(arg.status){ location.reload(); }else { $('#addError').text(arg.message); }}})})Copy the code
# urls

url(r'^modal_add_student/', views.modal_add_student),
Copy the code
# views

def modal_add_student(request):
    ret = {'status':True,'message':None}
    try:
        name = request.POST.get('name')
        print('result',name)
        class_id = request.POST.get('class_id')
        sqlheper.modify('insert into student (name,class_id)values(%s,%s)',[name,class_id,])
    except Exception as e:
        ret['status']=False
        ret['message']=str[e]
    return HttpResponse(json.dumps(ret))

Copy the code
  • Modal dialog box implementation changes
# HTML... <a class="btn-edit"> Dialog box edit </a>... <div ID ="editModal" class=" Add-Modal hide"> <h3> Edit student information </h3> <p> Name: <input type="text" name="name" id="editName" placeholder=" placeholder "> <input type="text" id="editId" style="display: <p> <p> Class:  <select id="editClassId" name="classId"> {% for row in class_list %} <option value="{{ row.id }}">{{ row.title </option> {% endfor %} </select> </p> <p> <input ID ="btnEdit" type="button" value=" update "/> <input ID ="btnEditCancle" <span id="editError" style="color: red;" ></span> </div>Copy the code
# css


.shadow{
    position: fixed;
    top: 0;
    bottom:0;
    left:0;
    right: 0;
    background-color: black;
    opacity: 0.5;
    z-index: 999;
}
.add-Modal{
    position: fixed;
    top:50%;
    left:50%;
    width: 400px;
    height: 300px;
    z-index: 1000;
    background-color: white;
    margin-left: -200px;
    margin-top: -200px;
}
.hide{
    display: none;
}

Copy the code
# js $(' BTN - edit '). Click (function () {# display data $(' # # shadow, editModal). RemoveClass (" hide "); var tds = $(this).parent().prevAll(); var studentId = $(tds[2]).text(); var studentName = $(tds[1]).text(); var classId = $(tds[0]).attr('clsid'); console.log(studentId,studentName,classId) $('#editId').val(studentId); $('#editName').val(studentName); $('#editClassId').val(classId); }); $('#btnEditCancle').click(function () { $('#shadow,#editModal').addClass('hide'); }) $(' # btnEdit). Click (function () {$# submit data. Ajax ({url: '/ modal_edit_student/' type: "POST", data: {' nid' : $('#editId').val(), 'name':$('#editName').val(),'class_id': $('#editClassId').val()}, dataType: 'JSON', //JSON.parse(arg) success:function(arg){ if(arg.status){ location.reload(); }else{ $('#editError').text(arg.message); }}})})Copy the code
# urls

url(r'^modal_edit_student/', views.modal_edit_student),
Copy the code
# views

def modal_edit_student(request):
    ret = {'status': True,'message': None}
    try:
        nid = request.POST.get('nid')
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlheper.modify('update student set name=%s,class_id=%s where id=%s',[name,class_id,nid,])
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))
Copy the code

Teacher management module

  • check
# urls

url(r'^teachers/', views.teachers),
Copy the code
Def teachers(request): teacher_list = sqlheper.get_list('select id,name from teacher',[]) teacher_list = sqlheper.get_list(""" select teacher.id as tid,teacher.name,class.title from teacher LEFT JOIN teacher2class on teacher.id = teacher2class.teacher_id  left JOIN class on class.id = teacher2class.class_id; """,[]) print(teacher_list) result = {} for row in teacher_list: tid =row['tid'] if tid in result: result[tid]['titles'].append(row['title']) else: result[tid] = {'tid': row['tid'],'name':row['name'],'titles': [row['title'],]} return render(request,'teacher.html',{'teacher_list':result.values()})Copy the code
# HTML < table border = "1" > < thead > < tr > < th > ID < / th > < th > teacher name < / th > < th > teaching class < / th > < th > action < / th > < / tr > < thead > < tbody > {% for  row in teacher_list %} <tr> <td>{{ row.tid }}</td> <td>{{ row.name }}</td> <td> {% for item in row.titles %} <span>{{ Endfor item}} < / span > {% %} < / td > < td > < a href = "/ edit_teacher? Nid = {{row. Dar}}" > edit < / a > < a > delete < / a > < / td > < / tr > {% endfor  %} </tbody> </table>Copy the code
  • increase
# ursl

url(r'^add_teacher/', views.add_teacher),
Copy the code
# views def add_teacher(request): if request.method == "GET": class_list = sqlheper.get_list('select id,title from class',[]) return render(request,'add_teacher.html',{'class_list': class_list}) else: Teacher_id = sqlheper.create('insert into teacher(name) ') teacher_id = sqlheper.create('insert into teacher(name) Values (%s)',[name,]) # insert data into class_ids = request.post.getList ('class_ids') # insert data into class_ids Data_list = [] for cls_id in class_ids: Temp = (teacher_id, CLs_id,) data_list.append(temp) obj = SQLheper.sqlHelper ( obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list) obj.close() return redirect('/teachers/')Copy the code
# HTML <h1> add teacher </h1> <form method="POST" action="/add_teacher/"> <p> /></p> <p> <select multiple size="10" name="class_ids"> {% for item in class_list %} <option value="{{ item.id }}">{{ Item. The title}} < option > {% endfor %} < / select > < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
  • change
<form method="POST" action="/edit_teacher/? nid={{ teacher_info.id }}"> <p><input type="text" name="name" value="{{ teacher_info.name }}" /></p> <p> <select name="class_ids" multiple size="10"> {% for item in class_list %} {% if item.id in class_id_list %} <option value="{{ item.id }}" selected>{{ item.title }}</option> {% else %} <option value="{{ item.id }}">{{ item.title }}</option> {% Endfor endif %} {% %} < / select > < / p > < input type = "submit" value = "submit" / > < / form >Copy the code
# urls

url(r'^edit_teacher/',views.edit_teacher),
Copy the code
# views def edit_teacher(request): if request.method == "GET": nid = request.GET.get('nid') obj = sqlheper.SqlHelper() teacher_info = obj.get_one('select id,name from teacher where id  =%s',[nid,]) class_id_list = obj.get_list('select class_id from teacher2class where teacher_id=%s',[nid,]) class_list = Obj. get_list('select id,title from class',[]) obj.close() print(' teacher_info ',teacher_info) Print (' class_id_list ',class_id_list) temp = [] for I in class_id_list: Temp. append(I ['class_id']) print(' all classes ',class_list) # return HttpResponse('... ') return render(request,'edit_teacher.html',{ 'teacher_info': teacher_info, 'class_id_list': temp, 'class_list': class_list, }) else: nid = request.GET.get('nid') name = request.POST.get('name') class_ids = request.POST.getlist('class_ids') obj = Modify ('update teacher set name=%s where id=%s',[name,nid]) # update teacher set name=%s where id=%s Delete the relationship between the current teacher and the class, Modify ('delete from teacher2class where teacher_id=%s',[nid,]) data_list = [] for cls_id in class_ids: temp = (nid,cls_id,) data_list.append(temp) obj = sqlheper.SqlHelper() obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list) obj.close() return redirect('/teachers/')Copy the code
  • Modal dialog box increment
# HTML <div ID ="shadow" class="shadow hide"></div> <div ID ="addModal" class="addModal hide">< p> name="name" id="addName"></p> <p> <select id="classIds" multiple="multiple" size="10"> </select> </p> <input Type ="button" id="addSubmit" value=" submit "> </div>Copy the code
# css

.shadow{
    position: fixed;
    top:0;
    bottom: 0;
    left:0;
    right: 0;
    background-color: black;
    opacity: 0.5;
    z-index: 999;
}
.addModal{
    position: fixed;
    width: 400px;
    height: 300px;
    top:50%;
    left:50%;
    margin-left: -200px;
    margin-top: -200px;
    background-color: white;
    z-index: 1000;
}
.hide{
    display: none;
}
Copy the code
# js $(function () { bindAdd(); bindAddSubmit(); }); function bindAdd() { $('#btnAdd').click(function () { $('#shadow,#addModal').removeClass('hide'); $.ajax({ url:'/get_all_class/', type:'GET', dataType:'JSON', success:function (arg) { $.each(arg,function(i,row){ var tag = document.createElement('option'); tag.innerHTML = row.title; tag.setAttribute('value',row.id); $('#classIds').append(tag); }); }})}); $('#cancle').click(function () { $('#shadow,#addModal').addClass('hide'); }) } function bindAddSubmit(){ $('#addSubmit').click(function(){ var name = $('#addName').val(); var class_id_list = $('#classIds').val(); console.log(name,class_id_list); $.ajax({ url:'/modal_add_teacher/', type: 'POST', data: {'name':name, 'class_id_list': Class_id_list}, dataType:'JSON', traditional: true,// function (arg) { if(arg.status){ location.reload(); }else{ alert(arg.message); }}})}); }Copy the code
# urls

url(r'^get_all_class/', views.get_all_class),
url(r'^modal_add_teacher/', views.modal_add_teacher),
Copy the code
# views def get_all_class(request): obj = sqlheper.SqlHelper() class_list = obj.get_list('select id,title from class',[]) return HttpResponse(json.dumps(class_list)) def modal_add_teacher(request): ret = {'status': True,'message': None} try: name = request.POST.get('name') class_id_list = request.POST.getlist('class_id_list') teacher_id = sqlheper.create('insert into teacher(name) values(%s)',[name,]) data_list = [] for cls_id in class_id_list: temp = (teacher_id,cls_id,) data_list.append(temp) obj = sqlheper.SqlHelper() obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list) obj.close() except Exception as e: Ret ['status'] = False ret['message'] = "failed to process" return HttpResponse(json. Dumps (ret))Copy the code
# sqlheper def create(sql,args): Conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql,args) conn.commit() last_row_id = cursor.lastrowid cursor.close() conn.close() return last_row_id class SqlHelper(object): Def __init__(self): self.connect() Self. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8') self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) def multiple_modify(self,sql,args): self.cursor.executemany(sql,args) self.conn.commit() def close(self): self.cursor.close() self.conn.close()Copy the code

The BOOTSTRAP framework

  • bootstrap
Download import project < link rel = "stylesheet" href = "/ static/plugins/bootstrap 3.3.7 - dist/CSS/bootstrap CSS" > according to the website content, add the corresponding class labelCopy the code

Fontawesome: same as above

Background Administration Layout (HTML master)

# manage.html <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" Href = "/ static/plugins/bootstrap 3.3.7 - dist/CSS/bootstrap CSS" / > < link rel = "stylesheet" /> <link rel="stylesheet" href="/static/ CSS /commons.css" /> {% block CSS %}{% endblock %} </head> <body> <div class="pg-header"> <div class="logo left"> </div> <div class="avatar right" style="position: Relative "> [picture outside the chain archived failure (ly4y20a img - 4-1562038376731) (https://mp.csdn.net/static/images/1.jpg)] < div class =" user - info "> Personal information < a > < / a > < a > logout < / a > < / div > < / div > < div class = "rmenus right" > < a > < I class = "fa fa - the commenting - o" aria - hidden = "true" > < / I > News < / a > < a > < I class = "fa fa - envelope - o" aria - hidden = "true" > < / I > email < / a > < / div > < / div > < div class = "pg - body" > < div Class = "menus" > < a > < I class = "fa fa - futbol - o" aria - hidden = "true" > < / I > class management < / a > < a > students tube < / a > < a > teacher management < / a > < / div > < div Class = "content" > < ol class = "breadcrumb" > < li > < a href = "#" > home page < / a > < / li > < li > < a href = "#" > class management < / a > < / li > < li Class class = "active" > add < / li > < / ol > {% block xx %} {% endblock %} < / div > < / div > {% block js %} {% endblock %}Copy the code
# css body{ margin: 0; } .left{ float: left; } .right{ float: right; } .hide{ display: none; } .pg-header{ height: 48px; min-width: 1190px; background-color: #204d74; line-height: 48px; } .pg-header .logo{ color: white; font-size: 18px; width: 200px; text-align: center; border-right: 1px solid #8a6d3b; } .pg-header .rmenus a{ display: inline-block; padding: 0 15px; color: white; } .pg-header .rmenus a:hover{ background-color: #269abc; } .pg-header .avatar{ padding: 0 20px; } .pg-header .avatar img{ border-radius: 50%; } .pg-header .avatar .user-info{ display: none; background-color: white; border: 1px solid #dddddd; position: absolute; width: 100px; top: 48px; right: 20px; color: white; z-index: 100; text-align: center; } .pg-header .avatar:hover .user-info{ display: block; } .pg-header .avatar .user-info a{ display: block; } .menus{ width: 200px; position: absolute; left: 0; bottom: 0; top: 48px; border-right: 1px solid #dddddd; background-color: #dddddd; } .content{ position: absolute; left: 200px; right: 0; top: 48px; bottom: 0; min-width: 990px; overflow: scroll; z-index: 99; } .pg-body .menus a{ display: block; padding: 10px 5px; border-bottom: 1px solid #ffffff; }Copy the code

User login (including cookies)

# html <form method="post" action="/login/"> <input type="text" name="username"> <input type="password" name="password"> < form> </form>Copy the code
# urls

url(r'^login/', views.login),
Copy the code
# views def login(request): if request.method == "GET": return render(request,'login.html') else: user = request.POST.get('username') pwd = request.POST.get('password') if user == 'tom' and pwd == '123': Obj = redirect('/classes/') obj.set_signed_cookie('ticket',"567",salt=' JJJJJ ',max_age=900,path='/') Return obj else: return render(request,'login.html') def classes(request): Tk = request.cookies. Get ('ticket') tk = request.get_signed_cookie('ticket',salt=' JJJJJ ') print(tk) if not tk: Return redirect('/login/') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,title from class") class_list = cursor.fetchall() cursor.close() conn.close() return render(request, 'classes.html', {'class_list': class_list})Copy the code
@xzxx def index(request): obj = HttpResponse('... ') obj.set_cookie(.....) request.COOKIES.get(...) obj.set_signed_cookie(.....) request.get_signed_cookie(....)Copy the code

Dynamic routing


urls

Dynamic routing # # url (r '^ edit/(\ w +)/(\ w +)/', views, edit), # url (r' ^ edit/(? P<a1>\w+)/(? P < a2 > \ w +)/', views, edit), # url (r '^ edit/(\ w +). The HTML $', views, edit) # realize static regular expressions in disguiseCopy the code

views

Def edit(request,*args,**kwargs): return HttpResponse('... ')Copy the code

Routing distribution


# Route distribution implements separate editing for different modules, Team development url(r'^app01/', include('app01.urls')),# different application module URL (r'^app02/', include('app02.urls')), # url(r'^', default), Url (r'^', views.index), #Copy the code

Reverse generation of urls (Django only)


Aliases are reflected as urls to simplify THE FILLING in of urls for permission management

#urls

url(r'^edit/(\w+)/(\w+)/', views.edit,name='n2'),
Copy the code
For I # HTML < ul > {% in user_list %} < li > {{I}} | < a href = "/ edit / {{I}} /" > edit < / a > < / li > < li > {{I}} | < a href = "{% url "N2" I 1%} "> edit < / a > < / li > # and 1 as the parameters in the url I {% endfor %} < / ul >Copy the code

ORM basic operations (table + row operations)


This section describes the configuration steps before the operation

Add: import pymysql pymysql.install_as_mysqldb ()Copy the code
Create a database manually in mysqlCopy the code
TEMPLATES = [... 'DIRS': [os.path.join(BASE_DIR,' TEMPLATES ')],...]  DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'s4day70db', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } }Copy the code

The operating table

  • Create a table
# models from django.db import models class UserInfo(models.Model): _UserInfo nID = models.BigAutoField(primary_key=True) Username = models.charfield (max_length=32) password = models.charfield (max_length=64)Copy the code
INSTALLED_APPS = [... 'app01',]Copy the code
Python Manage. py Makemigrations # Generate table configuration files, hoisting, and names Python manage.py Migrate # Execute generated configuration filesCopy the code
  • Modify the table:
# models class UserInfo(models.model):... # age = models.IntegerField(default=1) # age = models.IntegerField(null=True)Copy the code
Python Manage. py Makemigrations # Generate table configuration files, hoisting, and names Python manage.py Migrate # Execute generated configuration filesCopy the code
  • Delete table:
# refer to the modify tableCopy the code
  • Create a foreign key association:
# models class UserGroup(models.Model): Title = models.CharField(max_length=32) class UserInfo(models.model): Ug = models.ForeignKey('UserGroup', NULL =True,on_delete='"Copy the code
  • Operation on a single table row:
# increase the from app01 import models models. The UserGroup. Objects. The create (title = 'sales')Copy the code
# delete models. The UserGroup. Objects. The filter (id = 2). The delete ()Copy the code
# change models. The UserGroup. Objects. The filter (id = 2). The update (title = 'public relations')Copy the code
# check group_list = models. The UserGroup. Objects. All () group_list = models. The UserGroup. Objects. The filter group_list = (id = 1) Models. The UserGroup. Objects. The filter (id__gt = 1) # is greater than 1 group_list = models. The UserGroup. Objects. The filter (id__lt = 1) is less than # 1Copy the code

Django view CBV


urls

url(r'^login.html$', views.Login.as_view),
Copy the code

views

from django.views import View class Login(View): Def dispatch(self, request, *args, **kwargs): # Custom dispatch method, in addition to the parent class can use the original dispatch method, Print ('before') obj = super(Login,self).dispatch(request, *args, **kwargs) Print ('after') return obj def get(self,request): # return HttpResponse(' login.get ') return render(request,'login.html') def post(self,request): Print (request.post.get ('user')) return HttpResponse(' login.post ')Copy the code
<form method="POST" action="/login.html"> <input type="text" name="user" /> <input type="submit" value=" submit" /> </form>Copy the code

ORM join table operations (one-to-many) (in one-to-many, foreign keys exist in slave tables)


models

from django.db import models class UserType(models.Model): CharField(max_length=32) class UserInfo(models.model): Name = models.charfield (max_length=16) age = models.integerfield () ut = Models.foreignKey ('UserType',on_delete= ") # Associate the ID field in the UserType tableCopy the code

urls

url(r'^test.html$', views.test),
Copy the code

views

# # to create data models. The UserType. Objects. The create (title = 'ordinary users') # models. The UserType. Objects. The create (title =' asshole users') # Models. The UserType. Objects. The create (title = 'cow force users') # models. The UserInfo. Objects. The create (name =' party less wei, age = 18, ut_id = 1) # Models. The UserInfo. Objects. The create (name = 'by chi, age = 18, ut_id = 2) # models. The UserInfo. Objects. The create (name =' Liu Geng ', the age = 18, ut_id = 2) # Models. The UserInfo. Objects. The create (name = 'Chen tao ", the age = 18, ut_id = 3) # models. The UserInfo. Objects. The create (name =' king ', the age = 18, ut_id = 3) # Models. The UserInfo. Objects. The create (name = 'Yang Han', the age = 18, ut_id = 1)Copy the code
  • One-to-many forward operation (let slave tables with foreign keys cross tables to query fields in associated primary tables) :
Get Queryset object format data (format: object name) Foreign key field name. The associative table field name) obj = models. The UserInfo. Objects. All (). The first (#) to obtain a data, No longer obj [0] to obtain specific object print (obj. Name, obj. Age, obj. Ut. The title) # access across the table after the field with obj. Ut. The way of the title, ut is the foreign key fieldsCopy the code
Get query results in dictionary format combined into a list of Queryset data, using the list method to convert the list format (from table foreign key field name __ main table field name) v1 = models.UserInfo.objects.values('id','name','ut__title')Copy the code
Select * from Queryset; select * from Queryset; select * from List models.UserInfo.objects.all().values_list('id','name'.'ut__title')Copy the code
  • One-to-many reverse operation (let the primary table cross the table to query (with foreign key associated fields) from the corresponding field in the table as the query condition or query result) :
The Queryset name of the main table. Alter table __set.all(); alter table __set-all ();  obj = models.UserType.objects.all().first() for row in obj.userinfo_set.all(): print(row.name,row.age)Copy the code
Queryset = Queryset = Queryset; Convert a list of available list methods (lowercase __ the main table from the table name field name) v2 = models. The UserType. Objects. Values (' id ', 'title', 'userinfo__name')Copy the code
Queryset = Queryset = Queryset = Queryset = Queryset; (the foreign key field name __ from table field name) result = models. The UserType. Objects. All () values_list (' id ', 'name', 'userinfo__name')Copy the code
  • One to many other references:
SQL > alter table forward query  1. q = UserInfo.objects.all().first() q.ug.title 2. UserInfo.objects.values('nid','ug_id') Values (' nID ','ug_id','ug__title') 3. Userinfo.objects.values_list (' nID ','ug_id','ug__title')  1. All ().first() result = obj.userinfo_set.all() [userinfo object,userinfo object,] 2. Values ('id','title') v = usergroup.objects.values ('id','title',' lowercase slave table name ') v = usergroup.objects.values ('id','title',' lowercase slave table name ') v = Usergroup.objects. values('id','title',' lowercase slave name __age') 3. Values_list ('id','title') v = usergroup.objects.values_list (' ID ','title',' lowercase table name ') v = Usergroup.objects.values_list ('id','title',' lowercase table name __age')Copy the code

ORM join table operation (many-to-many)

In many-to-many, the foreign keys of the primary table and slave table co-exist in the third associated table


Create a third associated table manually (recommended, manual is more flexible)

# models from django.db import models class Boy(models.Model): name = models.CharField(max_length=32) class Girl(models.Model): nick = models.CharField(max_length=32) class Love(models.Model): b = models.ForeignKey('Boy',on_delete='') g = models.ForeignKey('Girl',on_delete='') class Meta: Unique_together = [('b','g'),]Copy the code
# views # Add data Objs = [models.Boy(name=' xj '), models.Boy(name=' xj '), models. Objs = [models.Girl(Nick =' fish '),] Models.boy.objects. Bulk_create (objs,5) # Model.girl.objects. Bulk_create (objss,5) # 1. Model.girl (Nick ='小周'), model.girl (Nick ='小周'), model.girl (Nick ='小周'), model.girl.objects. Query the girl who is related to Fang Shaowei. Reverse query across the table for # object obj = models. Boy. Objects. The filter (name = 'party less wei). The first () # love_list = obj. Love_set. All () # reverse query, # for row in love_list Print (row.g.ick) # print(row.g.ick) # print(row.g.ick) # print(row.g.ick) # print(row.g.ick) Inquiry table query (positive), query love table directly, to get # love_list = models. Love. Objects. The filter (b__name = 'party less wei) # # get Queryset objects for the row in love_list: # print(row.g.ick) # print(row.g.ick) # print(row.g.ick) Send only one SQL connection request, Get a dictionary, belongs to the forward query # love_list = models. Love. Objects. The filter (b__name = 'party less wei) values (' g__nick') # for the item in love_list: # get a dictionary format list [{' g__nick ':'}, XXX] # print (item [' g__nick ']) # (recommended) 4 kinds of query methods: This is equivalent to the inner join mode, where only one SQL join request is sent. Get object # love_list = models. Love. Objects. The filter (b__name = 'party less wei) select_related (' g') # for obj in love_list: Print (obj.g. Ick) # print(obj.g. Ick) # print(obj.g. Ick) # print(obj.g. Ick) # print(obj.g. Ick) # print(obj.g. Ick) # print(obj.gCopy the code

Django automatically generates a third associated table (you can’t add additional fields manually)

# models class Boy(models.Model): Name = models.charfield (max_length=32) m = models.manytomanyfield ('Girl') # Class Girl(models.model): Nick = models.charfield (max_length=32)Copy the code
# # # views to add obj = models. Boy. Objects. The filter (name = 'party less wei). The first () # obj. M. dd (2) # obj. M. dd (2, 4) create associative table multiple data # # # obj.m.remove(*[4,]) # obj.m.remove(*[4,]) # obj.m.remove(*[4,]) # obj.m.remove(*[4,]) # obj.m.remove(*[4,]) # obj.m.remove(*[4,]) # Obj. Margaret spellings et ([1]) # to cover all database data, reset # obj = models. Boy. Objects. The filter (name = 'party less wei). The first () # obj. M.c Lear () # # delete all associated with less wei of data Towards # # query out of a single data obj = models. Boy. Objects. The filter (name = 'party less wei). The first () # # girl_list = obj. M. ll () # girl_list = Girl_list (Nick = girl_list) # print(girl_list) # obj = Models. Girl. Objects. The filter (Nick = 'fish'). The first (#) print (obj. Id, obj. Nick) # boy_list = obj. Boy_set. All () # is equal to the table from across the table to reverse the query from the tableCopy the code

Manual and automatic combination

# models class Boy(models.Model): name = models.CharField(max_length=32) m = models.ManyToManyField(to='Girl',through="Love",through_fields=('b','g',)) # Class Girl(models.model): Nick = models.charfield (max_length=32) class Love(models.model): b = models.ForeignKey('Boy',on_delete='') g = models.ForeignKey('Girl',on_delete='') class Meta: unique_together = [ ('b','g'), ]Copy the code
# views obj = models. Boy. Objects. The filter (name = 'party less wei). The first () obj. M. dd (1) # obj. M.r emove (1) # obj. M.c Lear can v = () obj.m.all() print(v)Copy the code

ORM join table operations (many-to-many autocorrelation)


Principle: Equivalent to copying a new table

models

class UserInfo(models.Model): nickname = models.CharField(max_length=32) username = models.CharField(max_length=32) password = Models.CharField(max_length=64) gender_choices = ((1,' male '), ) gender = models.IntegerField(choices=gender_choices) m = Models.ManyToManyField('UserInfo') Fields from_userInfo_id and to_userInfo_id; The m attribute in the userinfo table does not generate m fieldsCopy the code
def test(request): # check boys (via m field belongs to positive action) xz = models. The UserInfo. Objects. The filter (id = 1). The first () with id # 1 is for boys 1 the data u = xz. M. ll () for a row in the u: Print (row. Nickname) # check girls (through the table name _set query belongs to the reverse operation) xz = models. The UserInfo. Objects. The filter (id = 4). The first () of 4 # id on behalf of the girl's v = 1 the data xz.userinfo_set.all() for row in v: print(row.nickname) return HttpResponse('... ')Copy the code

Foreign key autocorrelation (often used for comment table functionality)

It is equivalent to copying a new table and using the foreign key in the original table to join the table operation

class Comment(models.Model): """ news_id = models.integerfield () # newsid content = models.charfield (max_length=32) # Models.charfield (max_length=32) # commenter reply = Models.foreignKey ('Comment',null=True,blank=True,related_name=' XXXX ') #related_name Replace the name of the table _set and the name of the table __ field name "" news ID reply_id 1 1 don't compare root null 2 1 I compare root null 3 1 Shaowei null 4 2 write exactly root null 5 1 5 """ """ news 1 Don't bibi bibi - pull down - pull down 2 - pull down 1 blind bibi news 2: write just """Copy the code

ORM operations supplement (data table property definition operations in the Models module)


models

from django.db import models from django.core.validators import RegexValidator class UserAdmin(models.Model): username = models.CharField(max_length=32) email = models.EmailField(null=True,default='111', Db_index =True,unique=True, blank=True,verbose_name=' mailbox ', editable=True, help_text=' contents of fields ',) # blank controls whether admin is empty, File = models.fileField () # Test = models.charfield (max_length=32, error_messages={ 'c1': }, validators=[RegexValidator(regex='root_\d+', message=' error ', code='c1')], # num = models.integerField () # num = models.integerField () num = Models.DecimalField(max_digits=30,decimal_places=10) # Color_list = ((1,' black '), (2,' white '), (3,' blue ') color = models.IntegerField(choices=color_list) class Meta: Unique_together =(('email','username') index_together=(('email','username')Copy the code
Contrib import admin from app01 import models admin.site.register(models.useradmin)Copy the code

Paging query


Built-in paging function

  • urls
url(r'^index.html$', views.index),
Copy the code
  • views
from django.core.paginator import Paginator,Page,PageNotAnInteger,EmptyPage def index(request): User_list = models. The UserInfo. Objects. All () # all database data obtained paginator = paginator (user_list, 10) # set each page shows the total number of article current_page = Request.get.GET ('page')# post = paginator. Page (current_page) # save PageNotAnInteger as e: Posts = paginator. Page (1) except EmptyPage as e: Page (1) return render(request,'index.html',{'posts':posts})Copy the code
  • html
< h1 > user list < / h1 > < ul > {% for the row in posts. The object_list %} < li > {{row. The name}} < / li > {% endfor %} < / ul > < div > {% the if <a href="/index.html? Page ={{posts.previous_page_number}}"> </a> {% endif %} {% if <a href="/index.html? Page ={{posts.next_page_number}}"> </a> {% endif %} </div>Copy the code

Set the paging

  • urls
url(r'^custom.html$', views.custom),
Copy the code
  • views
from utils.pager import PageInfo
def custom(request):
    all_count = models.UserInfo.objects.all().count() 
    page_info = PageInfo(request.GET.get('page'),all_count,10,'/custom.html',11)
    user_list = models.UserInfo.objects.all()[page_info.start():page_info.end()]
    return render(request,'custom.html',{'user_list':user_list,'page_info':page_info})
Copy the code
  • PageInfo tools
class PageInfo(object): def __init__(self,current_page,all_count,per_page,base_url,show_page=11): ":param all_count: total number of database rows :param per_page: number of rows to be displayed per page: param base_URL: Self.current_page = int(current_page) except Exception as e: param show_page: self.current_page = int(current_page) except Exception as e: Self.current_page = 1 self.per_page=per_page a,b = divmod(all_count,per_page) # return a tuple containing the remainder and the business if b: There is more data than is needed after the total number of databases/pages. A = a+1 self.all_pager= a # show_page= show_page self.base_url= base_url # Start (self): return (self.current_page-1) * self.per_page # def end(self): Return self.current_page * self.per_page # def pager(self): Page_list =[] # if self.all_pager < 0 if self.all_pager < 0 if self.all_pager < 0 if self.all_pager < 0 if self.all_pager < 0 if self.all_pager < Self. show_page: begin =1 stop=self.all_pager + 1 else: 11 if self.current_page <= half: begin =1 stop = self.show_page + 1 else: if self.current_page + half > self.all_pager: begin = self.all_pager - self.show_page + 1 stop = self.all_pager + 1 else: Begin = self.current_page - half stop = self.current_page + half + 1 # if self.current_page <= 1: Prev = "< li > < a href = '#' > back < / a > < / li >" the else: prev = "< li > < a href = '% s? Page =%s'> </a></li>"%(self.base_URL, self.current_PAGe-1,) page_list.append(prev) # stop): if i == self.current_page: temp = "<li class='active'><a href='%s? page=%s'>%s</a></li>" % (self.base_url, i, i,) else: temp = "<li><a href='%s? page=%s'>%s</a></li>" % (self.base_url, i, I,) page_list.append(temp) # assemble 'next page' option if self.current_page >= self.all_pager: Nex = "< li > < a href = '#' > page < / a > < / li >" the else: nex = "< li > < a href = '% s? Page =%s'> next page </a></li>" %(self.base_url,self.current_page+1,) page_list.append(nex) return ". Join (page_list)Copy the code
  • html
< H1 > User list </ H1 > <ul> {% for row in user_list %} <li>{{row.name}}</li> {% endfor %} </ul> <nav ARIa-label ="Page navigation"> <ul class="pagination"> {{ page_info.pager|safe }} </ul> </nav>Copy the code