这里写目录标题
昨日回顾
1 视图层之请求对象
-request.method
-GET (不能修改,一改就抛异常)
-POST
-is_ajax()
-path
-get_full_path()
-FILES 字典
-META http请求中(大部分都是请求头,客户端的ip地址)
-body 请求体,二进制,传文件,取会抛异常
-request.COOKIE
-request.session
-request.user
2 视图层之响应对象
-本质都是HttpResponse('ok')
-四件套:JsonResponse
3 cbv和fbv
-路由配置:url('index/',类名.as_view())
-视图类
class 类名(View):
def get(self,request):
一毛一样
def post(self,request):
一毛一样
4 文件上传
-前端:input type=file name=myfile form表单的编码
-前端:ajax,postman,其它语言
-后端:
myfile=requset.FIELS.get('myfile')
打开一个空文件,一行一行的读,写入空文件
返回
今日内容
一 模版简介
你可能已经注意到我们在例子视图中返回文本的方式有点特别。 也就是说,HTML被直接硬编码在 Python代码之中。
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并不是一个好主意。 让我们来看一下为什么:
-
对页面设计进行的任何改变都必须对 Python 代码进行相应的修改。 站点设计的修改往往比底层 Python 代码的修改要频繁得多,因此如果可以在不进行 Python 代码修改的情况下变更设计,那将会方便得多。
-
Python 代码编写和 HTML 设计是两项不同的工作,大多数专业的网站开发环境都将他们分配给不同的人员(甚至不同部门)来完成。 设计者和HTML/CSS的编码人员不应该被要求去编辑Python的代码来完成他们的工作。
-
程序员编写 Python代码和设计人员制作模板两项工作同时进行的效率是最高的,远胜于让一个人等待另一个人完成对某个既包含 Python又包含 HTML 的文件的编辑工作。
基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。 我们可以使用 Django的 *模板系统* (Template System)来实现这种模式,这就是本章要具体讨论的问题
python的模板:HTML代码+模板语法
def current_time(req):
# ================================原始的视图函数
import datetime
now=datetime.datetime.now()
html="<html><body>现在时刻:<h1>%s.</h1></body></html>" %now
# ================================django模板修改的视图函数
from django.template import Template,Context
now=datetime.datetime.now()
t=Template('<html><body>现在时刻是:<h1>{{current_date}}</h1></body></html>')
#t=get_template('current_datetime.html')
c=Context({'current_date':str(now)})
html=t.render(c)
return HttpResponse(html)
#另一种写法(推荐)
#view.py
import datetime
def index(request):
now=datetime.datetime.now()
return render(request,'current_datetime.html',{'current_date':str(now)[:19]})
#current_datetime.html
<body>
现在时间是:<h1>{{ current_date }}</h1>
</body>
#url
url('curtime/',views.index),
模版语法重点:
变量:{{ 变量名 }}
1 深度查询 用句点符
2 过滤器
标签:{{% % }}
二、django模板使用的两种方式
# 方式一
return render(request,'time.html',context={'current_date':str(now),'title':'lqzNB'})
# 方式二(页面静态化,提高网站并发量)
now=datetime.datetime.now()
from day65 import settings
import os
path=os.path.join(settings.BASE_DIR,'templates','time.html')
ss=open(path,'r',encoding='utf-8').read()
t=Template(ss)
c=Context({'current_date':str(now),'title':'lqzNB'})
html=t.render(c) # html是渲染后的字符串
return HttpResponse(html)
三、前后端交互的三种编码格式
1 urlencoded---->传普通的数据,form表单默认就是这种---->request.POST
2 form-data-----》传文件和数据 ---->request.POST request.FILES
3 json----------》传json格式数据 ---->request.body中取出来自行处理
代码演示
接收urlencoded编码
视图函数:
def home(request):
return render(request,'home.html')
def index(request):
# 接收urlencoded编码
#body体中:name=lqz&age=18
print(request.POST)
return HttpResponse('ok')
home.html代码:
<body>
<h1>urlencoded编码</h1>
<form action="/index/" method="post">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
路由配置:
url('home/', views.home),
url('index/', views.index),
接收form-data编码
视图函数:
def home(request):
return render(request,'home.html')
def index(request):
print(request.POST)
print(request.FILES)
return HttpResponse('ok')
'''
body体中:分两部分,一部分是数据,一部分是文件
数据部分:name=lqz&age=18
---asdfasdfasdfgasgasgd---
文件部分(二进制)
#数据部分
# print(request.POST)
# #文件部分
# print(request.FILES)
'''
home.html代码:
<body>
<h1>from-data编码</h1>
<form action="/index/" method="post" enctype="multipart/form-data">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="file" name="myfile"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
路由配置:
url('home/', views.home),
url('index/', views.index),
接收json格式
form表单无法传json格式数据,要借助postman
body体中
{
"name": "lqz",
"age": 18
}
# 这里没有
print(request.POST)
# 数据在这(自行处理)
print(request.body)
运行结果:
b'{\r\n "name": "lqz",\r\n "age": 18\r\n\t}'
如图所示
四、cbv的本质
from django.views import View
class Index(View):
# 允许的请求方式列表
# http_method_names = ['post', 'get']
def dispatch(self, request, *args, **kwargs):
# 执行原来的dispatch
# 类似于装饰器
# 加代码
# res=super().dispatch(request, *args, **kwargs)
# # 加代码
# return res
# 不管什么请求来,都执行get
return self.get(request, *args, **kwargs)
# 没有dispatch方法,找父类,如果有会执行自己的
def get(self, request, *args, **kwargs):
print(request.data)
return HttpResponse('cbv的get请求')
def post(self, request, *args, **kwargs):
return HttpResponse('cbv的post请求')
# 了解
# from django.views.generic.base import View,TemplateView
# from django.views import View
# class Index(TemplateView):
# template_name='home.html'
# 1 请求来了,路由匹配成功执行 path('index/', views.Index.as_view()),
执行views.Index.as_view()()
# 2 本质是执行as_view()内部有个闭包函数view()
# 3 本质是view()---》dispatch()
# 4 dispatch内部,根据请求的方法(get,post)---->执行视图类中的def get def post
五、模板语法之变量
DTL:Django Template Language
views.py
1 模板中使用 {{python变量}}
############views.py
def index(request):
num = 10
ss = 'lqz is handsome'
b = False
ll = [1, 2, 43]
dic = {'name': 'lqz', 'age': 18}
def test():
print('我是test')
return 'test ---撒发射点'
class Person():
def __init__(self, name):
self.name = name
def print_name(self):
return self.name
def __str__(self):
return self.name
p=Person('lqz')
# return render(request, 'index.html',{'num':num,'ss':ss,'b':b})
#locals() 把当前作用域下所有的变量,都传到context中
return render(request, 'index.html',locals())
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ss}}</title>
</head>
<body>
<h1>模板语法之变量</h1>
<p>数字:{{ num }}</p>
<p>字符串:{{ ss }}</p>
<p>布尔:{{ b }}</p>
<p>列表:{{ ll }}</p>
<p>字典:{{ dic }}</p>
<p>函数:{{ test }}</p>
<p>对象:{{ p }}</p>
</body>
</html>
运行结果如下:
六、模板语法之深度查询句点符
views.py
def index(request):
num = 10
ss = 'lqz is handsome'
b = False
ll = [1, 2, 43, {'name': 'egon'}]
dic = {'name': 'lqz', 'age': 18}
def test():
print('我是test')
return 'test ---撒发射点'
class Person():
def __init__(self, name):
self.name = name
def print_name(self):
return self.name
def __str__(self):
return self.name
p = Person('lqz')
link1 = '<a href="https://www.baidu.com">点我<a>'
link2 = mark_safe(link1)
input_1='<p>用户名:<input type="text" name="name"></p>'
input_2=mark_safe(input_1)
script_1='''
<script>
alert('你被攻击了')
</script>
'''
script_2 =mark_safe(script_1)
return render(request, 'index.html', locals())
index.html
<h2>模板语法之句点符的深度查询</h2>
<p>列表的第一个元素:{{ ll.1 }}</p>
<p>字典的name对应的值:{{ dic.name }}</p>
<p>列表的第三个元素的name对应的值:{{ ll.3.name }}</p>
<p>函数执行,直接写函数名即可:{{ test }}</p>
<p>函数如果有参数?不支持</p>
<p>对象调用方法: {{ p.print_name }}</p>
<p>对象调用属性: {{ p.name }}</p>
<hr>
<a href="https://www.baidu.com">点我</a>
<p>a标签的字符串: {{ link1 }}</p>
<p>a标签的字符串,显示成a标签: {{ link2 }}</p>
<p>用户名:<input type="text" name="name"></p>
<p>input标签:{{ input_1 }}</p>
<p>input标签,显示成标签:{{ input_2 }}</p>
<p>js原封不动显示:{{ script_1 }}</p>
{{ script_2 }}
运行结果:
七、模板渲染成标签还是原封不动的字符串
# xss攻击:是什么,如何预防?django已经处理了xss攻击,它的处理原理是什么
from django.utils.safestring import mark_safe
link1 = '<a href="https://www.baidu.com">点我<a>'
link2 = mark_safe(link1)
{link1|safe}
八、模版之过滤器
语法:
{{obj|filter__name:param}} 变量名字|过滤器名称:变量
default
如果一个变量是false或者为空,使用给定的默认值。否则,使用变量的值。例如:
{{ value|default:``"nothing"` `}}
<p>default:{{ num|default:'没有值' }}</p>
length
返回值的长度。它对字符串和列表都起作用。例如:
{{ value|length }}
<p>length:{{ l1|length }}</p>
<p>length:{{ dic|length }}</p>
<p>length:{{ 'qwe'|length }}</p>
如果 value 是 [‘a’, ‘b’, ‘c’, ‘d’],那么输出是 4。
filesizeformat
将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB'
, '4.1 MB'
, '102 bytes'
, 等等)。例如:
{{ value|filesizeformat }}
如果 value
是 123456789,输出将会是 117.7 MB
。
date
如果 value=datetime.datetime.now()
{{ value|date:``"Y-m-d"` `}}
slice
如果 value=“hello world”
{{ value|``slice``:``"2:-1"` `}}
truncatechars
如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“…”)结尾。
**参数:**要截断的字符数
例如:
{{ value|truncatechars:``9` `}}
safe
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:
value``=``"<a href="``">点击</a>"
{{ value|safe}}
view.py
def index(request):
num=''
ss = 'lqz is handsome'
b = False
l1=[1,2,34,{'name':'egon'}]
dic={'name':'lqz','age':18}
def test():
print('我是test')
return 'test ---撒发射点'
class Person():
def __init__(self, name):
self.name = name
def print_name(self):
return self.name
def __str__(self):
return self.name
p = Person('lqz')
link1='<a herf="https://www.baidu.com">点我</a>'
link2=mark_safe(link1)
input_1='<p>用户名:<input type="text" name="name"></p>'
input_2=mark_safe(input_1)
script_1='''
<script>
alert('你被攻击了')
</script>
'''
script_2=mark_safe(script_1)
ctime = datetime.datetime.now()
return render(request, 'ht.html', locals())
index.html
<h1>过滤器</h1>
<p>过滤器之default:{{ num|default:'没有值' }}</p>
<p>过滤器之length:{{ ll|length }}</p>
<p>过滤器之length:{{ dic|length }}</p>
<p>过滤器之length:{{ 'das'|length }}</p>
{# 模板语法的注释 #}
<!--
前端html的注释
-->
了解
<p>过滤器之filesizeformat:{{ num|filesizeformat }}</p>
lqz is handsome
<p>过滤器之slice:{{ ss|slice:"7:11" }}</p>
第二个参数写0,1,2, 都是 ..., 最少从3开始
<p>过滤器之truncatechars:{{ ss|truncatechars:'30' }}</p>
<p>truncatewords:{{ ss|truncatewords:'2' }}</p>
记住
<p>过滤器之date:{{ ctime|date:'Y年m月d日-------H时i分s秒' }}</p>
<p>过滤器之safe:{{ link1|safe }}</p>
其它过滤器(了解)
过滤器 | 描述 | 示例 |
---|---|---|
upper | 以大写方式输出 | {{ user.name | upper }} |
add | 给value加上一个数值 | {{ user.age | add:”5” }} |
addslashes | 单引号加上转义号 | |
capfirst | 第一个字母大写 | {{ ‘good’| capfirst }} 返回”Good” |
center | 输出指定长度的字符串,把变量居中 | {{ “abcd”| center:”50” }} |
cut | 删除指定字符串 | {{ “You are not a Englishman” | cut:”not” }} |
date | 格式化日期 | |
default | 如果值不存在,则使用默认值代替 | {{ value | default:”(N/A)” }} |
default_if_none | 如果值为None, 则使用默认值代替 | |
dictsort | 按某字段排序,变量必须是一个dictionary | {% for moment in moments | dictsort:”id” %} |
dictsortreversed | 按某字段倒序排序,变量必须是dictionary | |
divisibleby | 判断是否可以被数字整除 | {{ 224 | divisibleby:2 }} 返回 True |
escape | 按HTML转义,比如将”<”转换为”<” | |
filesizeformat | 增加数字的可读性,转换结果为13KB,89MB,3Bytes等 | {{ 1024 | filesizeformat }} 返回 1.0KB |
first | 返回列表的第1个元素,变量必须是一个列表 | |
floatformat | 转换为指定精度的小数,默认保留1位小数 | {{ 3.1415926 | floatformat:3 }} 返回 3.142 四舍五入 |
get_digit | 从个位数开始截取指定位置的数字 | {{ 123456 | get_digit:’1’}} |
join | 用指定分隔符连接列表 | {{ [‘abc’,’45’] | join:’’ }} 返回 abc45 |
length | 返回列表中元素的个数或字符串长度 | |
length_is | 检查列表,字符串长度是否符合指定的值 | {{ ‘hello’| length_is:’3’ }} |
linebreaks | 用 或 | {{ “Hi\n\nDavid”|linebreaks }} 返回 Hi David |
linebreaksbr | 用 标签代替换行符 | |
linenumbers | 为变量中的每一行加上行号 | |
ljust | 输出指定长度的字符串,变量左对齐 | {{‘ab’|ljust:5}}返回 ‘ab ’ |
lower | 字符串变小写 | |
make_list | 将字符串转换为列表 | |
pluralize | 根据数字确定是否输出英文复数符号 | |
random | 返回列表的随机一项 | |
removetags | 删除字符串中指定的HTML标记 | {{value | removetags: “h1 h2”}} |
rjust | 输出指定长度的字符串,变量右对齐 | |
slice | 切片操作, 返回列表 | {{[3,9,1] | slice:’:2’}} 返回 [3,9] {{ 'asdikfjhihgie' | slice:':5' }} 返回 ‘asdik’ |
slugify | 在字符串中留下减号和下划线,其它符号删除,空格用减号替换 | {{ '5-2=3and5 2=3' | slugify }} 返回 5-23and5-23 |
stringformat | 字符串格式化,语法同python | |
time | 返回日期的时间部分 | |
timesince | 以“到现在为止过了多长时间”显示时间变量 | 结果可能为 45days, 3 hours |
timeuntil | 以“从现在开始到时间变量”还有多长时间显示时间变量 | |
title | 每个单词首字母大写 | |
truncatewords | 将字符串转换为省略表达方式 | {{ 'This is a pen' | truncatewords:2 }}返回``This is ... |
truncatewords_html | 同上,但保留其中的HTML标签 | {{ '<p>This is a pen</p>' | truncatewords:2 }}返回``<p>This is ...</p> |
urlencode | 将字符串中的特殊字符转换为url兼容表达方式 | {{ ‘http://www.aaa.com/foo?a=b&b=c’ | urlencode}} |
urlize | 将变量字符串中的url由纯文本变为链接 | |
wordcount | 返回变量字符串中的单词数 | |
yesno | 将布尔变量转换为字符串yes, no 或maybe | {{ True | yesno }}{{ False | yesno }}{{ None | yesno }} ``返回 ``yes``no ``maybe |
九、标签(for,for … empty,if,with,csrf_token)
标签看起来像是这样的: {% tag %}
。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。一些标签需要开始和结束标签 (例如{% tag %} ...
标签 内容 … {% endtag %})。
for标签
遍历每一个元素:
{% for person in person_list %}
<p>{{ person.name }}</p>
{% endfor %}
可以利用{% for obj in list reversed %}
反向完成循环。
遍历一个字典:
{% for key,val in dic.items %}
<p>{{ key }}:{{ val }}</p>
{% endfor %}
注:循环序号可以通过{{forloop}}显示
forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)forloop.parentloop 本层循环的外层循环
for … empty[ ]
for
标签带有一个可选的{% empty %}
从句,以便在给出的组是空的或者没有被找到时,可以有所操作。
{% for person in person_list %}
<p>{{ person.name }}</p>
{% empty %}
<p>sorry,no person here</p>
{% endfor %}
if 标签
{% if %}
会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。
{% if num > 100 or num < 0 %}
<p>无效</p>
{% elif num > 80 and num < 100 %}
<p>优秀</p>
{% else %}
<p>凑活吧</p>
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
with
使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的
例如:
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}不要写成as
csrf_token
{% csrf_token%}
这个标签用于跨站请求伪造保护
总结:
1 {% 标签名 %}
2 标签for ,在标签for的内部一直有一个forloop对象,是个字典
counter0:从0开始,每循环一次加1
counter:从1开始,每循环一次加1
revcounter:从列表长度开始,每循环一次减一
first:判断是不是循环的第一个
last:判断是不是循环的最后一个
parentloop:父级forloop对象(for循环嵌套)
{'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 6, 'revcounter0': 5, 'first': True, 'last': False}
3 if标签
4 with标签(了解)
5 csrf标签(了解)
# views.py
def index(request):
ll=['lqz','egon','zs','ls','ww']
# ll=[]
dic={'name':'lqz','age':19}
count=1
lqzisnbplus='lqz'
# b=False
b=True
user_list=[{'name':'lqz','age':19},{'name':'egon','age':18},{'name':'张三','age':22},{'name':'李四','age':99},{'name':'asdfasdf','age':18},{'name':'暗室逢灯n','age':18}]
return render(request, 'index.html', locals())
#index.html
<h1>模板语法之标签</h1>
<h2>for的用法</h2>
{% for l in ll %}
{# <p>{{ l }}</p>#}
<p><a href="http://127.0.0.1:8080/{{ l }}">{{ l }}</a></p>
{% endfor %}
<hr>
{% for k,v in dic.items %}
<p>key值为:{{ k }},value值为{{ v }}</p>
{% endfor %}
<table border="1">
<tr>
<td>id号</td>
<td>用户名</td>
<td>年龄</td>
</tr>
{% for dic in user_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ dic.name }}</td>
<td>{{ dic.age }}</td>
</tr>
{% endfor %}
</table>
<hr>
<h2>for ----empty的用法</h2>
<ul>
{% for l in ll %}
<li>{{ l }}</li>
{% empty %}
<li>没有数据</li>
{% endfor %}
</ul>
<h2>forloop对象</h2>
{% for dic in user_list %}
{% for key,value in dic.items %}
{{ forloop.parentloop.counter }}
<p>{{ key }}:{{ value }}</p>
{% endfor %}
{% endfor %}
<h2>if</h2>
{% if b %}
<p>b是true的</p>
{% else %}
<p>b是false的</p>
{% endif %}
<h2>with重命名</h2>
{% with forloop.parentloop.counter as aaa %}
{{ aaa }}
{% endwith %}
{% with lqzisnbplus as a %}
{{ a }}
----{{ lqzisnbplus }}
{% endwith %}
<h2>csrf</h2>
{% csrf_token %}
<input type="text" name="csrfmiddlewaretoken" value="uC35XuP1J2Va74ArYiNw4TMZ0PaZ6V4qvVGCsUQcqiKF5Sr8IrWS0rzpmOmPBrjY">
</body>
拓展
1 http响应头响应头
content-type:text/html; charset=utf-8 # 返回数据的编码类型
2 http请求头,请求编码格式
urlencoded
form-data
jason
3 易混的点
xss攻击
csrf攻击
cors(先不用看):跨域资源共享,跟上面一毛钱关系都没有
作业
1 django设置响应头 name=lqz(如何设置)
2 写一个装饰器,用在视图函数上,不管前端用什么编码方式传数据,数据部分都从request.data中取
3 xss是什么?django已经处理了xss攻击,它的处理原理是什么
4 模板语法通过for和if渲染表格,如果是第一行,显示红色,最后一行显示绿色
5 csrf攻击是什么,如何防范(django也处理了)
6 讲的内容整理成博客
7 在第四个的基础上,显示用户浏览日志的功能,如果是第一行,显示红色,最后一行显示绿色