1. 程式人生 > >Python Django 前後端資料互動 之 HttpResponse、render、redirect

Python Django 前後端資料互動 之 HttpResponse、render、redirect

在使用三神裝的時候,首先當然是得要匯入它們: from django.shortcuts import HttpResponse, render, redirect

1、HttpResponse

它是作用是內部傳入一個字串引數,然後發給瀏覽器。 例如: def index(request):     # 業務邏輯程式碼     return HttpResponse("OK")  

2、render

render方法可接收三個引數,一是request引數,二是待渲染的html模板檔案,三是儲存具體資料的字典引數。 它的作用就是將資料填充進模板檔案,最後把結果返回給瀏覽器。與jinja2類似。 例如: def index(request):     # 業務邏輯程式碼     return render(request, "index.html", {"name": "monicx", "hobby": ["reading", "blog"]})  

3、redirect

接受一個URL引數,表示讓瀏覽器跳轉去指定的URL. 例如: def index(request):     # 業務邏輯程式碼     return redirect("https://blog.csdn.net/miaoqinian")