day52 summary

JsonResponse objects

  • White will be three axes: HTTPResponse, render, redirect

  • View function must have a return value, the return value and

  • Data type must be the object HTTPResponse

  • render: Template + Context

    def test(request):
        from django.template import Template, Context
        html_obj = Template('<h1>{{user}}</h1>')
        data_obj = Context({'user': {'user_name': 'jason'}})
        complete_html = html_obj.render(data_obj)
        return HttpResponse(complete_html)

Separate front and rear ends

  • Front and rear ends adopted for data interaction json, string dictionary

  • Url rear end of the corresponding written interfaces, front-access this interface,

  • The back-end to front-end returns a large dictionary, along with developer documentation

  • According to the front page rendering large dictionary of data and development documents

  • Front and rear ends of the sequence deserialization method used

    • python backend: json.dumps, json.loads
    • js前端: JSON.stringify, JSON.parse
  • Json not automatically set up for Chinese transcoding

    • Method 1: View json.dumps source code -> found ensure_ascii parameters, set its value to False

      def test(request):
          import json
          user_dic = {'name': '蔡启龙'}
          json_str = json.dumps(user_dic, ensure_ascii=False)  # {"name": "蔡启龙"}
          return HttpResponse(json_str)  # {"name": "\u8521\u542f\u9f99"}
    • Second way: using django package JsonResponse

      View JsonResponse source code -> find json.dumps -> parameter values ​​estimated json_dumps_params

      def test(request):
          from django.http import JsonResponse
          user_dic = {'name': '蔡启龙'}  # {"name": "\u8521\u542f\u9f99"}
          return JsonResponse(user_dic, json_dumps_params={'ensure_ascii': False})  # {"name": "蔡启龙"}
  • Provided other data types can be serialized serialized json

    According to the error message, change the parameters: safe = False

    def test(request):
        from django.http import JsonResponse
        lt = [1, 2]
        return JsonResponse(lt, safe=False)  # [1, 2]
    # In order to allow non-dict objects to be serialized set the safe parameter to False.

CBV and source code analysis

CBV: based on the view class, Class Based Views

  • FBV: Function Based Views, based on the view function
  • FBV wording: + view routing function name, url(r'^index/', views.index)
  • CBV wording: url(r'^login/', views.MyLogin.as_view())# return view, the cbv nature or fbv, routing function name +

CBV source code, requirements: to speak directly to the process

CBV why the request according to different methods, different methods automate

  • Priority function name in parentheses highest execution
  • A project started, it will automatically execute as_view method
  • Just look at the source code he can read it, do not read entangled in part
  1. The method of performing class as_view (), returns view
  2. Regular expression matching to "login /", execute view (),
  3. view () returns the dispatch (request, ...),
  4. Performing dispatch (request, ...), will get the request of the character string, by a method of finding objects reflection
  5. If found, the recording method to the handler, the function will not find a record for an error handler, and returns the results of the handler for an HttpResponse
from django.views import View


class MyLogin(View):
    def get(self, request):
        print('MyLogin的get方法')
        return render(request, 'login.html')

    def post(self, request):
        return HttpResponse('MyLogin的post方法')
@classonlymethod
def as_view(cls, **initkwargs):
    def view(request, *args, **kwargs):  # as_view内的闭包函数
        self = cls(**initkwargs)  # cls为自定义的MyLogin类, self为自定义的类实例化出的对象
        return self.dispatch(request, *args, **kwargs)

    return view


def dispatch(self, request, *args, **kwargs):
    if request.method.lower() in self.http_method_names:  # 判断当前请求方式是否在八个默认的方法内
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)  # 以get请求为例, getattr(obj, 'get')
    else:
        handler = self.http_method_not_allowed  # 调用get方法
    return handler(request, *args, **kwargs)  # 返回调用get方法的到的结果, 一个HttpResponse对象

CBV add to the decorator way

from functools import wraps
import time


def deco(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        exec_time = time.time() - start_time
        print('函数执行时间: %s' % (exec_time,))
        return res

1: Direct decoration

'''
@deco
def get(self, request):
    ...
'''

Second way: Using the built-in module, without using the built-in modules based directly on the decoration being given: 'function' object has no attribute 'as_view'

from django.utils.decorators import method_decorator

'''
@method_decorator(deco, name='post')
class MyLogin(View):
    ...

@method_decorator(deco)  # 推荐写法
def get(self, request):
    ...
'''

Three ways: all methods in class disposable added to decorators, if you want to do something before the view function is executed, the method can be customized dispatch be achieved in CBV

from django.utils.decorators import method_decorator


@method_decorator(deco, name='dispatch')
class MyLogin(View):
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

Template syntax

Template syntax format

Two kinds: {} {} related variables related logic %% {} {}

Template by value

You can pass data types, python basic data types support

def test(request):
    lt = [1, 2, 3]
    s = 'hello world'
    file_len = 666666
    tag = "<h1>tag</h1>"
    user_dic = {'name': 'jason', 'pwd': '123'}

    def index():
        return 'index的函数返回值'

    class TestClass:
        pass

    test_obj = TestClass()

    # locals会将当前名称空间中的所有名字传递给html页面
    return render(request, 'test.html', locals())
  • Transfer function names: <p>{{ index }}</p>

    When the HTML page to pass a function name, it will automatically call the function, and the function returns the value displayed, but does not support function parameter passing

  • Chuan class name: Auto bracketing instantiated to produce an object, as long as all are callable object passed to the html page will automatically call the brackets

    '''
    <p>{{ TestClass }}</p>
    <p>{{ test_obj }}</p>
    
    <app02.views.test.<locals>.TestClass object at 0x0000028D321F9F28>
    <app02.views.test.<locals>.TestClass object at 0x0000028D321EAD30>
    '''

filter

Some built-in method template syntax provides for fast data processing, but can only have two parameters

Will | the left of the data when the first argument as a filter incoming ":" the right of the data passed as the second parameter

  • Statistical Length: <p>{{ lt|length }}</p>, # 3, if you can not return to the default statistics 0

  • Adder: <p>{{ s|add:'nick' }}</p>, # Hello worldnick

  • Slicing operation: <p>{{ lt|slice:'0:2:1' }}</p>, # [1, 2], care regardless of the end, also supported steps, but not the negative index

  • Converted into a format file size: <p>{{ file_len|filesizeformat }}</p>, # 651.0 KB

  • Interception text: <p>{{ s|truncatechars:5}}</p>, # of He ..., intercepted five characters, and three points can be considered

  • Interception five words, according to the space, not three points: truncatewords

  • Determine whether there is value: <p>{{ ''|default:'为空时的默认值' }}</p># the default value of space-time, non-empty display original value, empty display defaults

  • Display text with the label:

    Does not automatically turn into a front-end html tag by default, to prevent malicious attacks

    If you want to identify the html syntax, you can set the front or rear set unescaping

    '''
    前端设置取消转义
        <p>{{ tag }}</p>  # <h1>tag</h1>
        <p>{{ tag|safe }}</p>  # tag
    '''
    
    # 后端设置取消转义
    from django.utils.safestring import mark_safe
    safe_tag = mark_safe(tag)
    # <p>{{ safe_tag }}</p>  # tag

label

Label refers to a set of code associated with the logic, such as if determined, and so the cycle for the label

for loop

'''
forloop对象: 
    first/last判断for循环的开始与结束
    count0, 从0开始的索引值
    counter, 对数据进行的计数, 例如解决主键值不连续

{% for num in lt %}
    <p>{{ forloop }}</p>
{% endfor %}

{'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 3, 'revcounter0': 2, 'first': True, 'last': False}
...
'''

if the judge

{% if s %}
    <p>s有值</p>
 {% else %}
    <p>s没有值</p>
{% endif %}

Combination

{% for num in lt %}
    {% if forloop.first %}
        <p>第一循环, 数字为: {{ num }}</p>
    {% elif forloop.last %}
        <p>最后一次循环, 数字为: {{ num }}</p>
    {% else %}
        <p>中间循环, 数字为: {{ num }}</p>
    {% endif %}
    {% empty %}
        <p>for循环对象为空时触发</p>
{% endfor %}

Dictionary for loop

'''
{% for key in user_dic.keys %}
    <p>{{ key }}</p>
{% endfor %}  # name  pwd

{% for value in user_dic.values %}
    <p>{{ value }}</p>  # jason  123
{% endfor %}

{% for item in user_dic.items %}
    <p>{{ item }}</p>  # ('name', 'jason')  ('pwd', '123')
{% endfor %}
'''

Template syntax values

Only one way, the uniform application period characters:. ""

'''
complex_dic = {'name': 'json', 'hobby': ['read', ['run', {'music': 'if you'}]]}
<p>{{ complex_dic.hobby.1.1.music }}</p>  # if you, 获取music的值

# 数据获取方式复制时使用别名, 但是别名只能在with内部使用
{% with complex_dic.hobby.1.1.music as music %}
    <p>{{ music }}</p>
{% endwith %}
'''

Custom filters and labels

Defined filters may be used in the logical statement, and not a custom label, the label is also common symbols {} %%

Since the former definition must have a three-step preparation:

  1. In the name of the application must name a new folder called templatetages
  2. Py file in the folder, create an arbitrary name
  3. Write two code under the py file: from django.template import Library,register = Library()

Custom filter:

# 自定义过滤器
@register.filter(name='division')
def handle(x, y):  # 跟默认过滤器一样, 最多接收两个参数
    return x / y

Use custom filter

The file must first load the filter is located over similar import

{% load my_filters_tags %}
{{ 1|division:10 }}

Custom label

You may receive any number of parameters

# 自定义标签
@register.simple_tag(name='my_tag')
def handle(a, b, c):
    return '%s?%s?%s' % (a, b, c)

Use custom labels

Receiving a plurality of parameters must be separated by a space

'''
{% load my_filters_tags %}
{% my_tag 'c' 'q' 'l' %}  # c?q?l
'''

Custom inclusion_tag

  1. Is a function to receive external parameters passed, and then passed to a fragment of html
  2. The data acquisition and rendering html fragment
  3. Finally, the rendered html fragment returned to the calling inclusion_tag place
# 自定义inclusion_tag
@register.inclusion_tag('part_html.html')
def inclusion_tag(n):
    lt = []
    for i in range(n):
        lt.append('第%s项' % (i,))
    return locals()  # 将lt传递给html片段

Use inclusion_tag, important

Scenario: When you need to use some page components, and the page component needs dynamic rendering parameters

'''
part_html.html
<ul>
    {% for ele in lt %}
        <li>{{ ele }}</li>
    {% endfor %}
</ul>

test.html
{% load my_filters_tags %}
{% inclusion_tag 3 %}
'''

Inherited template

It requires prior demarcated region in the HTML page you want to use, after the succession, you can use the designated areas, or can not modify any of the content

There are at least three general regions, html code region, css region, js region

  1. By block on the parent page template syntax defined areas
  2. On the sub-page template syntax extends through inheritance parent page
  3. In the area of ​​sub-pages using the block you want to modify selected template syntax
{% extends 'test.html' %}

{% block css %}
    <style>
        h1 {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <h1>登录页面</h1>
    {{ block.super }}  {#    在子页面上沿用父页面的内容#}
{% endblock %}

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

Importing templates

Html fragment as a module directly into the use of

And inclusion_tag difference:

  • Import template is to write dead, it does not support mass participation,
  • Inclusion_tag support and parameter passing, dynamic rendering HTML fragment can be based on different parameters
'''
test111.html:
    <h1>这是一个特别好看的form表单</h1>

{% block content %}
    {% include 'test111.html' %}
{% endblock %}
'''

Guess you like

Origin www.cnblogs.com/-406454833/p/11970245.html
Recommended