視圖
url
Django中url匹配是寫在 urls.py 文件中,用正則表達式對應 views.py 中的一個函數(shù)
配置url和對應視圖函數(shù)之間的映射
url(r'^$', views.index),
url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),
url(r'^manage/(?P<name>\w*)', views.manage,{'id':333}),
url(r'^web/',include('web.urls')), 根據(jù)app對路由規(guī)則進行一次分類
視圖
一個視圖函數(shù),簡稱視圖,是一個簡單的Python 函數(shù),它接受Web請求并且返回Web響應。
下面是一個返回當前日期和時間作為HTML文檔的視圖:
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
快捷函數(shù)
render(request, template_name[, context][, context_instance][, content_type][, status][, current_app][, dirs][, using])
request 必選參數(shù)
用于生成響應的請求對象。
status
響應的狀態(tài)碼。默認為200。
redirect(to, [permanent=False, ]*args, **kwargs)
裝飾器
require_http_methods(request_method_list)[source]
限制視圖只能服務規(guī)定的http方法。用法:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
pass
require_GET()
只允許視圖接受GET方法的裝飾器。
require_POST()
只允許視圖接受POST方法的裝飾器。
require_safe()
只允許視圖接受 GET 和 HEAD 方法的裝飾器。 這些方法通常被認為是安全的,因為方法不該有請求資源以外的目的。
請求和響應對象
Django 使用Request 對象和Response 對象在系統(tǒng)間傳遞狀態(tài)。
HttpRequest.method
一個字符串,表示請求使用的HTTP 方法。必須使用大寫。例如:
if request.method == 'GET':
do_something()
elif request.method == 'POST':
do_something_else()
HttpRequest.path 一個字符串,表示請求的頁面的完整路徑,不包含域名。
HttpRequest.POST 一個類似于字典的對象,如果請求中包含表單數(shù)據(jù),則包含HTTP POST 的所有參數(shù)。
HttpRequest.COOKIES 一個標準的Python 字典,包含所有的cookie。鍵和值都為字符串。
HttpRequest.FILES 一個類似于字典的對象,包含所有的上傳文件。FILES 中的每個鍵為<input type="file" name="" /> 中的name。
JsonResponse 對象
典型的用法如下:
from django.http import JsonResponse
response = JsonResponse({'foo': 'bar'})
文件上傳
當Django在處理文件上傳的時候,文件數(shù)據(jù)被保存在request. FILES
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網(wǎng)站欄目:django-視圖-創(chuàng)新互聯(lián)
當前地址:http://aaarwkj.com/article18/piodp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、定制開發(fā)、品牌網(wǎng)站設計、App設計、服務器托管、標簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容