1. 程式人生 > >from django.shortcuts import render之django.shortcuts原始碼解析

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 簡化這個程式設計過程。