框架Django番外篇
Posted nayike
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了框架Django番外篇相关的知识,希望对你有一定的参考价值。
一.中间件
django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件。
代码:
MIDDLEWARE = [ \'django.middleware.security.SecurityMiddleware\', \'django.contrib.sessions.middleware.SessionMiddleware\', \'django.middleware.common.CommonMiddleware\', \'django.middleware.csrf.CsrfViewMiddleware\', \'django.contrib.auth.middleware.AuthenticationMiddleware\', \'django.contrib.messages.middleware.MessageMiddleware\', \'django.middleware.clickjacking.XFrameOptionsMiddleware\', ]
1.过程
#可用于:1.黑名单 2.免登陆
2.2.自定义中间件
代码:
1.注册中间件(settings.py)
MIDDLEWARE = [ \'django.middleware.security.SecurityMiddleware\', \'django.contrib.sessions.middleware.SessionMiddleware\', \'django.middleware.common.CommonMiddleware\', \'django.middleware.csrf.CsrfViewMiddleware\', \'django.contrib.auth.middleware.AuthenticationMiddleware\', \'django.contrib.messages.middleware.MessageMiddleware\', \'django.middleware.clickjacking.XFrameOptionsMiddleware\', \'m1.Middle1\', \'m1.Middle2\', ]
2.创建中间件(m1.py:)
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse #中间件 一 class Middle1(MiddlewareMixin): def process_request(self, request): print(\'m1.process_request\') # return HttpResponse(\'不要在往下周了\') def process_response(self, request, response): print(\'m1.process_response\') return response #中间件 二 class Middle2(MiddlewareMixin): def process_request(self, request): print(\'m2.process_request\') # return HttpResponse(\'不要在往下周了\') def process_response(self, request, response): print(\'m2.process_response\') return response
执行结果:
3.路由关系的匹配
3.1.路由
3.1.1单一路由
rom django.conf.urls import url from django.contrib import admin from app01.views import love from app01.views import account urlpatterns = [ url(r\'^admin/\', admin.site.urls), url(r\'^login.html$\',account.login), url(r\'^logout.html$\',account.logout), url(r\'^index.html$\',love.index), url(r\'^others.html$\',love.others), ]
3.1.2 基于正则的路由
url(r\'^index/(\\d*)\', views.index), url(r\'^manage/(?P<name>\\w*)/(?P<id>\\d*)\', views.manage),
3.1.3 添加额外的参数
url(r\'^manage/(?P<name>\\w*)\', views.manage,{\'id\':333}),
3.1.4为路由映射设置名称
url(r\'^home\', views.home, name=\'h1\'), url(r\'^index/(\\d*)\', views.index, name=\'h2\'),
3.1.5路由分发
urls.py url(r\'^app01/\', include(\'app01.urls\')), app01.urls.py url(r\'^index.html$\', views.index),
3.2 url(r\'^admin/\', admin.site.urls)的 admin
django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,就可以对数据进行增删改查
3.2.1创建一个用户
3.2.2向admin中增加一栏 UserInfo
3.2.3效果
4.函数(模版和数据渲染)
4.1模版
4.1.1模版的执行
模版的创建过程,对于模版,其实就是读取模版(其中嵌套着模版标签),然后将 Model 中获取的数据插入到模版中,最后将信息返回给用户。
4.1.2模版语言
•{{ item }} •{% for item in item_list %} <a>{{ item }}</a> {% endfor %} forloop.counter forloop.first forloop.last •{% if ordered_warranty %} {% else %} {% endif %} •母板:{% block title %}{% endblock %} 子板:{% extends "base.html" %} {% block title %}{% endblock %} •帮助方法: {{ item.event_start|date:"Y-m-d H:i:s"}} {{ bio|truncatewords:"30" }} {{ my_list|first|upper }} {{ name|lower }}
4.2自定义simple_filter ,simple_tag (模板自定义函数)
a、在app中创建templatetags模块
b、创建任意 .py 文件,如:xx.py
from django import template register = template.Library() #register 一词固定写法 @register.filter def my_upper(value): return value.upper() @register.filter def my_u(value,arg): return value+arg @register.filter def my_bool(value): return False @register.simple_tag def my_lower(value,a1,a2,a3): return value + a1 + a2 + a3
c、在使用自定义simple_tag的html文件中导入之前创建的 xx.py 文件名
{% load xx %} {# 导入此句 #} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>打印字典所有的key</h1> {{ name|my_upper }} {{ name|my_u:\'666\' }} <h2>filter</h2> {{ name|my_u:"666" }} {% if name|my_bool %} <h3>真</h3> {% else %} <h3>假</h3> {% endif %} <h2>tag</h2> {% my_lower "ALEX" "x" "SB" "V" %} </body> </html>
d、在settings中配置当前app,不然django无法找到自定义的simple_tag
INSTALLED_APPS = ( \'django.contrib.admin\', \'django.contrib.auth\', \'django.contrib.contenttypes\', \'django.contrib.sessions\', \'django.contrib.messages\', \'django.contrib.staticfiles\', \'app01\', )
4.3母版
4.3.1layout.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" /> <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" /> <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"> <img style="width: 40px;height: 40px;" src="/static/images/1.jpg"> <div class="user-info"> <a>个人资料</a> <a>注销</a> </div> </div> <div class="rmenus right"> <a><i class="fa fa-commenting-o" aria-hidden="true"></i> 消息</a> <a><i class="fa fa-envelope-o" aria-hidden="true"></i> 邮件</a> </div> </div> <div class="pg-body"> <div class="menus"> <a> <i class="fa fa-futbol-o" aria-hidden="true"></i> 班级管理</a> <a>学生管</a> <a>老师管理</a> </div> <div class="content"> <ol class="breadcrumb"> <li><a href="#">首页</a></li> <li><a href="#">班级管理</a></li> <li class="active">添加班级</li> </ol> {% block xx %}{% endblock %} </div> </div> {% block js %}{% endblock %} </body> </html>
4.3.2index,html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for row in posts.object_list %} <li>{{ row.name }}</li> {% endfor %} </ul> <div> {% if posts.has_previous %} <a href="/index.html?page={{ posts.previous_page_number }}">上一页</a> {% endif %} {% if posts.has_next %} <a href="/index.html?page={{ posts.next_page_number }}">下一页</a> {% endif %} </div> </body> </html>
#笔记内容
layout.html {% block x1 %}{%endblock%} <h1>ff</h1> {% block x2 %}{%endblock%} <h1>2</h1>... {% block x3 %}{%endblock%} index.html {%extends \'layout\'%} {% block x1 %}dfssssssdfsd{%endblock%} {% block x2 %}dfsdfsd{%endblock%} {% block x3 %}fff{%endblock%}
4.4include
a.pub.html(只有一个 div)
<div> <h3>特别漂亮的组件</h3> <div> <div class="title">标题:</div> <div class="content">内容:</div> </div> </div>
b.在另一个.html中,引入使用
% load xx %} {# 导入此句 #} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% include \'pub.html\' %} {% include \'pub.html\' %} {% include \'pub.html\' %} {% include \'pub.html\' %} {# <h1>打印字典所有的key</h1>#} {##} {# {{ name|my_upper }}#} {# {{ name|my_u:\'666\' }}#} {##} {##} {##} {# <h2>filter</h2>#} {# {{ name|my_u:"666" }}#} {##} {# {% if name|my_bool %}#} {# <h3>真</h3>#} {# {% else %}#} {# <h3>假</h3>#} {# {% endif %}#} {# <h2>tag</h2>#} {# {% my_lower "ALEX" "x" "SB" "V" %}#} </body> </html>
#笔记内容
1. 模板 - 基本使用 - 母版 - 页面继承 - include - 导入小组件 pub.html <div> <h3>特别漂亮的组件</h3> <div class="title">标题:{{ name }}</div> <div class="content">内容:{{ name }}</div> </div> test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> {% include \'pub.html\' %} {% include \'pub.html\' %} {% include \'pub.html\' %} </body> </html> - 函数-> 自动执行 - 模板自定义函数: - simple_filter - 最多两个参数,方式: {{第一个参数|函数名称:"第二个参数"}} - 可以做条件判断 - simple_tag - 无限制: {% 函数名 参数 参数%}
4.8 ORM
4.8.1 Http请求:
url -----> 视图(模版+数据)
4.8.2 步骤:
1.在mysql,创建数据库
2.
3.
4.8.3 ORM操作表:
创建表
修改表
删除表
操作数据行:
增删改查
4.8.4 ORM利用pymysql第三方工具连接数据库
默认:
SQLlite
MySQL:
mysql -> MySQLDB(修改django默认连接mySQL方式)
4.8.5 数据类型
# 数据获取多个数据时 # 1. [obj,obj,obj,] # models.UserInfo.objects.all() # models.UserInfo.objects.filter(id__gt=1) # result = models.UserInfo.objects.all() # for item in result: # print(item.name,item.ut.title) # 2. [{id:1,name:fd},{id:1,name:fd},{id:1,name:fd},] # models.UserInfo.objects.all().values(\'id\',\'name\') # models.UserInfo.objects.filter(id__gt=1).values(\'id\',\'name\') # 无法跨表 # result = models.UserInfo.objects.all().values(\'id\',\'name\') # for item in result: # print(item[\'id\'],item[\'name\']) # 夸表 __ # result = models.UserInfo.objects.all().values(\'id\',\'name\',"ut__title") # for item in result: # print(item[\'id\'],item[\'name\'],item[\'ut__title\']) # 3. [(1,df),(2,\'df\')] # models.UserInfo.objects.all().values_list(\'id\',\'name\') # models.UserInfo.objects.filter(id__gt=1).values_list(\'id\',\'name\') # 无法跨表 # result = models.UserInfo.objects.all().values_list(\'id\',\'name\') # for item in result: # print(item[0],item[1])0 # 夸表 __ # result = models.UserInfo.objects.all().values_list(\'id\',\'name\',"ut__title") # for item in result: # print(item[0],item[1],item[2])
4.8.6 操作
# 1.增删改查 # 2. 一般: # models.UserInfo.objects.filter(id__gt=1) # models.UserInfo.objects.filter(id__lt=1) # models.UserInfo.objects.filter(id__lte=1) # models.UserInfo.objects.filter(id__gte=1) # models.UserInfo.objects.filter(id__in=[1,2,3]) # models.UserInfo.objects.filter(id__range=[1,2]) # models.UserInfo.objects.filter(name__startswith=\'xxxx\') # models.UserInfo.objects.filter(name__contains=\'xxxx\') # models.UserInfo.objects.exclude(id=1) # 3. 排序 user_list = models.UserInfo.objects.all().order_by(\'-id\',\'name\') # 4. 分组 from django.db.models import Count,Sum,Max,Min # v =models.UserInfo.objects.values(\'ut_id\').annotate(xxxx=Count(\'id\')) # print(v.query) # v =models.UserInfo.objects.values(\'ut_id\').annotate(xxxx=Count(\'id\')).filter(xxxx__gt=2) # print(v.query) # v =models.UserInfo.objects.filter(id__gt=2).values(\'ut_id\').annotate(xxxx=Count(\'id\')).filter(xxxx__gt=2) # print(v.query) # 5. F,更新时用于获取原来的值 # from django.db.models import F,Q # models.UserInfo.objects.all().update(age=F("age")+1) # 6. Q,用于构造复杂查询条件 # 应用一: # models.UserInfo.objects.filter(Q(id__gt=1)) # models.UserInfo.objects.filter(Q(id=8) | Q(id=2)) # models.UserInfo.objects.filter(Q(id=8) & Q(id=2)) # 应用二: # q1 = Q() # q1.connector = \'OR\' # q1.children.append((\'id__gt\', 1)) # q1.children.append((\'id\', 10)) # q1.children.append((\'id\', 9)) # # # q2 = Q() # q2.connector = \'OR\' # q2.children.append((\'c1\', 1)) # q2.children.append((\'c1\', 10)) # q2.children.append((\'c1\', 9)) # # q3 = Q() # q3.connector = \'AND\' # q3.children.append((\'id\', 1)) # q3.children.append((\'id\', 2)) # q2.add(q3,\'OR\') # # con = Q() # con.add(q1, \'AND\') # con.add(q2, \'AND\') # models.UserInfo.objects.filter(con) # 7. extra, 额外查询条件以及相关表,排序 models.UserInfo.objects.filter(id__gt=1) models.UserInfo.objects.all() # id name age ut_id models.UserInfo.objects.extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) # a. 映射 # select # select_params=None # select 此处 from 表 # b. 条件 # where=None # params=None, # select * from 表 where 此处 # c. 表 # tables # select * from 表,此处 # c. 排序 # order_by=None # select * from 表 order by 此处 models.UserInfo.objects.extra( select={\'newid\':\'select count(1) from app01_usertype where id>%s\'}, select_params=[1,], where = [\'age>%s\'], params=[18,], order_by=[\'-age\'], tables=[\'app01_usertype\'] ) """ select app01_userinfo.id, (select count(1) from app01_usertype where id>1) as newid from app01_userinfo,app01_usertype where app01_userinfo.age > 18 order by app01_userinfo.age desc """ result = models.UserInfo.objects.filter(id__gt=1).extra( where=[\'番外篇-Prometheus入门OpenCV-Python实战(番外篇)——基于 Haar 级联的猫脸检测器