TemplateResponse dan``SimpleTemplateResponse``

Standard HttpResponse objects are static structures. They are provided with a block of pre-rendered content at time of construction, and while that content can be modified, it isn't in a form that makes it easy to perform modifications.

However, it can sometimes be beneficial to allow decorators or middleware to modify a response after it has been constructed by the view. For example, you may want to change the template that is used, or put additional data into the context.

TemplateResponse provides a way to do just that. Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the template and context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.

Obyek SimpleTemplateResponse

class SimpleTemplateResponse

Atribut

SimpleTemplateResponse.template_name

Nama dari cetakan untuk dibangun. Menerima obyek cetakan tergantung-backend (seperti itu dikembalikan oleh get_template()), nama dari cetakan, atau daftar dari nama-nama cetakan.

Contoh: ['foo.html', 'path/to/bar.html']

SimpleTemplateResponse.context_data

Data konteks untuk digunakan ketika membangun cetakan. Itu harus berupa dict.

Contoh: {'foo': 123}

SimpleTemplateResponse.rendered_content

Nilai dibangun saat ini dari isi tanggapan, menggunakan cetakan saat ini dan data konteks.

SimpleTemplateResponse.is_rendered

Sebuah boolean menunjukkan apakah tanggapan isi dapat dibangun.

Cara

SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)

Memberi contoh obyek SimpleTemplateResponse dengan cetakan diberikan, konteks, jenis isi, keadaan HTTP, dan charset.

template
Sebuah obyek cetakan bergantung-backend (seperti itu dikembalikan oleh get_template()), nama dari cetakan, atau daftar dari nama-nama cetakan.
context
Sebuah dict dari nilai-nilai untuk menambahkan konteks cetakan. Secara awalan, ini adalah dictionary kosong.
content_type
The value included in the HTTP Content-Type header, including the MIME type specification and the character set encoding. If content_type is specified, then its value is used. Otherwise, 'text/html' is used.
status
Kode keadaan HTTP untuk tanggapan.
charset
Charset dimana tanggapan akan disandikan. Jika tidak diberikan itu akan dikeluarkan dari content_type, dan jika itu tidak berhasil, pengaturan DEFAULT_CHARSET akan digunakan.
menggunakan
NAME dari mesin cetakan untuk digunakan untuk memuat cetakan.
headers
A dict of HTTP headers to add to the response.
Changed in Django 3.2:

The headers parameter was added.

SimpleTemplateResponse.resolve_context(context)

Preprocesses context data that will be used for rendering a template. Accepts a dict of context data. By default, returns the same dict.

Timpa metode ini untuk menyesuaikan konteks.

SimpleTemplateResponse.resolve_template(template)

Menyelesaikan contoh cetakan untuk digunakan untuk membangun. Menerima obyek cetakan bergantung-backend (seperti itu dikembalikan oleh get_template()), nama dari cetakan, atau daftar dari nama-nama cetakan.

Mengembalikan contoh obyek cetakan bergantung-backend untuk dikirim.

TImpa metode ini untuk menyesuaikan pemuatan cetakan.

SimpleTemplateResponse.add_post_render_callback()

Add a callback that will be invoked after rendering has taken place. This hook can be used to defer certain processing operations (such as caching) until after rendering has occurred.

Jika SimpleTemplateResponse sudah dibangun, callback akan dipanggil segera.

Ketika dipanggil, callback akan melewatkan argumen tunggal -- instance SimpleTemplateResponse terbangun.

If the callback returns a value that is not None, this will be used as the response instead of the original response object (and will be passed to the next post rendering callback etc.)

SimpleTemplateResponse.render()

Sets response.content to the result obtained by SimpleTemplateResponse.rendered_content, runs all post-rendering callbacks, and returns the resulting response object.

render() will only have an effect the first time it is called. On subsequent calls, it will return the result obtained from the first call.

Obyek TemplateResponse

class TemplateResponse

TemplateResponse is a subclass of SimpleTemplateResponse that knows about the current HttpRequest.

Cara

TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)

Instantiates a TemplateResponse object with the given request, template, context, content type, HTTP status, and charset.

request
Sebuah instance HttpRequest.
template
Sebuah obyek cetakan bergantung-backend (seperti itu dikembalikan oleh get_template()), nama dari cetakan, atau daftar dari nama-nama cetakan.
context
Sebuah dict dari nilai-nilai untuk menambahkan konteks cetakan. Secara awalan, ini adalah dictionary kosong.
content_type
The value included in the HTTP Content-Type header, including the MIME type specification and the character set encoding. If content_type is specified, then its value is used. Otherwise, 'text/html' is used.
status
Kode keadaan HTTP untuk tanggapan.
charset
Charset dimana tanggapan akan disandikan. Jika tidak diberikan itu akan dikeluarkan dari content_type, dan jika itu tidak berhasil, pengaturan DEFAULT_CHARSET akan digunakan.
menggunakan
NAME dari mesin cetakan untuk digunakan untuk memuat cetakan.
headers
A dict of HTTP headers to add to the response.
Changed in Django 3.2:

The headers parameter was added.

Pengolahan membangun

Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.

Ada tiga keadaan dibawah mana TemplateResponse akan dibangun:

  • Ketika contoh TemplateResponse secara tegas dibangun, menggunakan metode SimpleTemplateResponse.render().
  • Ketika isi dari tanggapan secara tegas disetel dengan memberikan response.content.
  • Setelah melewatkan melalui cetakan tanggapan middleware, tetapi sebelum melewatkan melalui tanggapan middleware.

Sebuah TemplateResponse hanya dapat dibangun sekali. Panggilan pertama pada SimpleTemplateResponse.render() mensetel isi dari tanggapan; selanjutnya membangun panggilan untuk tidak merubah isi tanggapan.

Bagaimanapun, ketika response.content secara tegas diberikan, perubahan selalu diberlakukan. Jika anda ingin memaksa isi untuk dibangun-kembali, anda dapat menilai-kembali isi dibangun, dan berikan isi dari tanggapan secara manual:

# Set up a rendered TemplateResponse
>>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {})
>>> t.render()
>>> print(t.content)
Original content

# Re-rendering doesn't change content
>>> t.template_name = 'new.html'
>>> t.render()
>>> print(t.content)
Original content

# Assigning content does change, no render() call required
>>> t.content = t.rendered_content
>>> print(t.content)
New content

Callback pasca-dibangun

Beberapa tindakan - seperti menyimpan sementara - tidak dapat dilakukan pada cetakan yang belum dibangun. Mereka harus dilakukan pada sepenuhnya lengkap dan tanggapan yang dibangun.

If you're using middleware, you can do that. Middleware provides multiple opportunities to process a response on exit from a view. If you put behavior in the response middleware, it's guaranteed to execute after template rendering has taken place.

Bagaimanapun, jika anda sedang menggunakan penghias, kesempatan sama tidak ada. Perilaku apapun ditentukan dalam sebuah penghias ditangani segera.

Untuk mengimbangi ini (dan penggunaan kasus sejalan lainnya), TemplateResponse mengizinkan anda mendaftarkan callback yang akan dipanggil ketika pembangunan lengkap. Menggunakan callback ini, anda dapat menunda pengolahan kritis sampai titik dimana anda dapat menjamin bahwa isi dibangun akan tersedia.

To define a post-render callback, define a function that takes a single argument -- response -- and register that function with the template response:

from django.template.response import TemplateResponse

def my_render_callback(response):
    # Do content-sensitive processing
    do_post_processing()

def my_view(request):
    # Create a response
    response = TemplateResponse(request, 'mytemplate.html', {})
    # Register the callback
    response.add_post_render_callback(my_render_callback)
    # Return the response
    return response

my_render_callback() akan diminta setelah mytemplate.html telah dibangun, dan akan disediakan sepenuhnya contoh TemplateResponse dibangun sebagai sebuah argumen.

Jika cetakan sudah dibangun, callback akan diminta segera.

Menggunakan TemplateResponse dan SimpleTemplateResponse

A TemplateResponse object can be used anywhere that a normal django.http.HttpResponse can be used. It can also be used as an alternative to calling render().

For example, the following view returns a TemplateResponse with a template and a context containing a queryset:

from django.template.response import TemplateResponse

def blog_index(request):
    return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})