from django.shortcuts import render之django.shortcuts源码解析

django.shortcuts 是一个包,django.shortcuts源码

from django.http import (
    Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import Promise

django.shortcuts的头不难看出它引入很多基础性的 东西。
先看一下render的源码

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

然后看一render的案例

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {
        'foo': 'bar',
    }, content_type='application/xhtml+xml')

然后看一个实现相同功能的对比

from django.http import HttpResponse
from django.template import loader

def my_view(request):
    # View code here...
    t = loader.get_template('myapp/index.html')
    c = {'foo': 'bar'}
    return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')

返回的结果都为 content 和content_type

简单的说来 就是render 把模板’myapp/index.html’ 和数据 ‘foo’: ‘bar’ 内容 渲染在了一起返回给了前台。

django.shortcuts render 简化这个编程过程。

你可能感兴趣的:(Django)