day 52 Summary

View layer

White will be three tricks
HttpResponse
render
redirect

View function must have a return value and return value data types have HttpResponse object

JsonResponse

Separating the front and rear ends of
the front and rear ends data on how interactions?
Are json string (dictionary) end of the data before and after interacting normally used in
back-end need only write the appropriate front-end interface to access the url you this interface
you just need to return a large dictionary + development documentation can be
used to tell you this interface front-end engineers capable of what data is returned

Front and rear ends are sequence deserialization which method

python backend The front js
json.dumps JSON.stringify
json.loads JSON.parse
from django.http import JsonResponse
def index(request):
    user_dic = {'name':'jason好帅哦 我好喜欢~','password':'123'}
    # 如何让json不自动帮你对中文进行转码
    # json_str = json.dumps(user_dic,ensure_ascii=False)
    # return HttpResponse(json_str)
    # return JsonResponse(user_dic,json_dumps_params={'ensure_ascii':False})
    l = [1,2,3,4,5,6,7,]
    # JsonResponse默认是序列化字典用的 如果你想序列化其他数据类型(json模块能够序列化的) 你需要加一个safe参数
    return JsonResponse(l,safe=False)       

FBV and CBV

FBV: view function based view of the base class: CBV

from dajongo.views import View
    class MyLogin(View):
        def get(self,request):
            print('我是MyLogin里面的get方法')
            return render(request,'login.html')

        def post(self,request):
            print('我是MyLogin里面的post方法')
            return HttpResponse('post')
        
        # 路由的写法 与CBV有点不同
            # FBV写法 路由>>> 视图函数内存地址
            url(r'^index/',viiews.index)
            # CBV写法
            url(r'^login/',views.MyLogin.as_view())
            # CBV在路由匹配上 其实本质还是FBV

CBV source code (must be able to do directly say the process)
thinking: Why CBV can be executed in different ways depending on the mode of the automatic request?

# 访问属性和方法
# 方法就是函数 (函数名加括号执行优先级最高)
# 项目一启动 会自动执行as_viiew方法
def as_view(cls, **initkwargs):
    def view(request, *args, **kwargs):  # 闭包函数
        self = cls(**initkwargs)  # cls是我们自己写的类 MyLogin  self是我们自己定义的类的对象
        # 在看源码的时候 你一定要把握住一个顺序 对象在查找属性和方法的时候
        # 先从对象自身找 再去产生对象的类中找 再去类的父类中找
        return self.dispatch(request, *args, **kwargs)
    return view


def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    # 判断当前请求方式在不在默认的八个方法内
    # 1.先以GET请求为例
    if request.method.lower() in self.http_method_names:
        # 利用反射去我们自己定义类的对象中查找get属性或者是方法  getattr(obj,'get')
        # handler = get方法
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
            return handler(request, *args, **kwargs)  # 调用get方法

CBV add to the decorator is recommended that you use the built-in module

from django.utils.decorators import method_decorator
from django.views import View
# 2.可以指定给谁装
# @method_decorator(outter,name='post')
# @method_decorator(outter,name='dispatch')
class MyLogin(View):
    @method_decorator(outter)
    def dispatch(self, request, *args, **kwargs):  # 如果你想在视图函数执行之前 做一些操作 你可以在你的CBV中定义dispatch方法来拦截

        return super().dispatch(request,*args,**kwargs)
    # @outter  # 1.直接写
    # @method_decorator(outter)  # 1.推荐写法
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')
    # @outter
    def post(self,request):
        print('我是MyLogin里面的post方法')
        time.sleep(1)
        return HttpResponse('post')

Template layer

Template syntax
only two writing format

{{}}    # 变量相关
{%%}    # 逻辑相关(url)

Template by value

python all basic data types supported by value

<p>传函数名:    {{ index }}
    给HTML页面传函数名的时候  模板语法会自动加括号调用该函数 并且将该函数的含绘制当作展示依据    模板语法不支持函数传参 也就意味着   你传给html页面的可能是不需要传参数调用的函数
</p>

<P>传类名:{{ MyClass }}
    自动加括号实例化产生对象
</P>
<p>传对象:{{ obj }}</p>
<p>{{ obj.get_self }}</p>
<p>{{ obj.get_cls }}</p>
<p>{{ obj.get_func }}</p>
<p>总结:只要是能够加括号调用的 传递到html页面上都会自动加括号调用</p>

Filter grammatical structure:
template syntax also provides you with some built-in method to help you quickly process data

Most two parameters

== == front end unescaping

The default is not automatically help you convert the front end of the front end html tag to prevent malicious attacks
| safe

{#<p>展示带有标签的文本:{{ sss|safe }}</p>#}
{#<p>展示带有标签的文本:{{ sss1|safe }}</p>#}

rear end

from django.utils.safestring import mark_safe
sss2 = "<h2>我的h2标签</h2>"
res = mark_safe(sss2)

The filter template syntax

Automatically | first parameter data of the current filter incoming left: the right as the second parameter

{#<p>统计长度(如果无法统计默认返回0):{{ s|length }}</p>#}
{#<p>加法运算(内部异常捕获 支持数字相加 字符串拼接 都不符合返回空):{{ n|add:f }}</p>#}
{#<p>切片操作 顾头不顾尾 也支持步长:{{ l|slice:'0:5:2' }}</p>#}
{#<p>判断是否有值(有值展示值本身 没值展示默认值):{{ is_value|default:'is_value变量名指向的值为空' }}</p>#}
{#<p>自动转成文件大小格式:{{ file_size|filesizeformat }}</p>#}
{#<p>截取文本内容(字符) 截取五个字符 三个点也算:{{ s|truncatechars:8 }}</p>#}
{#<p>截取文本内容(按照空格计算) 截取五个单词 三个点不算 :{{ s1|truncatewords:5 }}</p>#}

Tags logically related

for + tablecan display objects you need to loop

IF
for loop

for if used in combination

{% for foo in l %}
    {% if forloop.first %}
        <p>这是我的第一次</p>
    {% elif forloop.last %}
        <p>这是最后一次</p>
    {% else %}
        <p>{{ foo }}</p>
    {% endif %}
    {% empty %}
        <p>当for循环的对象是空的时候会走</p>
    {% endfor %}

<p>模板语法的取值 只有一种方式 同一采用句点符</p>
<p>{{ comp_dic.hobby.2.2.age}}</p>

<p>当你的数据是通过比较复杂的点点点获取的后续又经常要使用,你可以给给该数据取别名</p>
{% with comp_dic.hobby.2.2.age as age %}
    <p>{{ age }}</p>
{% endwith %}

Custom filters and labels

django supports user-defined
must have a three-step preparation
1. In an application under the name of a new name to be called templatetags folder
2. Create an arbitrary name of the file in the folder py file
3. The file py you must write down the following two codes

After the register can be defined using filters and labelsfrom django.template import Library
register = Library()

from django.template import Library

register = Library()            # 必须这样写

Using a custom filter

Now you need to load the html page

# 自定义过滤器    跟默认的过滤器一样   最多只能接收两个参数
@register.filter(name='baby')
def index(a,b):
    return a + b

# 自定义标签 可以接受任意多个参数
@register.simple_tag(name='mytag')
def mytag(a,b,c,d):
    return '%s?%s?%s?%s'%(a,b,c,d)

Custom inclusion_tag

It is a function to receive external parameters passed in a html page and then passed to
the page rendering is complete after the data acquisition
will render the page into a good place to call inclusion_tag

# 自定义inclusion_tag
@register.inclusion_tag('mytag.html',name='xxx')
def index666(n):
    1 = []
    for i in range(n):
        l.append('第%s项'%i)
    return locals() # 将1直接传递给mytag.html页面

Custom filters using

{#<p>自定义过滤器的使用</p>#}
{#{% load mytag %}#}
{#{{ 1|baby:1  }}#}
{#{{ 1|baby:100  }}#}

{#<p>自定义标签的使用 可以接受多个参数 参数与参数之间必须空格隔开</p>#}
{#{% load mytag %}#}
{#{% mytag 'a' 'b' 'c' 'd' %}#}
{#{% load mytag %}#}
{##}
{#<p>自定义的过滤器可以在逻辑语句使用 而自定义的标签不可以</p>#}
{#{% if mytag '1' '2' '3' '4' %}#}
{#    <p>有值</p>#}
{#    {% else %}#}
{#    <p>无值</p>#}
{#{% endif %}#}

<p>自定义inclusion_tag的使用  当你需要使用一些页面组件的时候 并且该页面组件需要参数才能够正常渲染 你可以考虑使用inclusion_tag</p>
{% load mytag %}
{% xxx 5 %}

Inherited template

You need to be demarcated area now after inheriting the time you can use your designated area on the page that you want to use
means that if you do not designate any area then you will not be able to modify page content

{% block content %}
{% endblock %}
先在页面上利用block划定你以后可能想改的区域

继承之后  就可以通过名字找到对应的区域进行修改
{% extends 'home.html' %}

{% block content %}
修改模板中content区域内容
{% endblock %}

Scalability The more block area on the page template, the stronger
we suggest you have a template page at least three areas

css区域
html代码区域    可以设置多个block
js区域

With these three regions will be able to implement each page has its own separate css and js code

{% extends 'home.heml' %}

{% block css %}
    <style>
        p {
            color: green;
        }
    </style>
{% endblock %}

{% block content %}
<p>login页面</p>
{% endblock %}

{% block js %}
    <script>
        alert('login')
    </script>
{% endblock %}

You can also continue to use the content on the parent page on the sub-pages
{{ block.super }}

Inherited template

1. On the first page you want to inherit the block demarcated by you might have to change the future of the region
2. First inheritance extends on a sub-page
3. Using block content automatically prompted to select the area you want to modify

Importing templates

The html page as a module directly into use

{% include ‘borm.html’ %}

Guess you like

Origin www.cnblogs.com/LZF-190903/p/11939230.html