django-視圖

視圖

    url

        Django中url匹配是寫在 urls.py 文件中,用正則表達式對應 views.py 中的一個函數

        配置url和對應視圖函數之間的映射

        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')), 根據app對路由規則進行一次分類

視圖

一個視圖函數,簡稱視圖,是一個簡單的Python 函數,它接受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)

快捷函數

render(request, template_name[, context][, context_instance][, content_type][, status][, current_app][, dirs][, using])

request 必選參數

用於生成響應的請求對象。

status

響應的狀態碼。默認爲200。

redirect(to, [permanent=False, ]*args, **kwargs)


裝飾器

require_http_methods(request_method_list)[source]

限制視圖只能服務規定的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 對象在系統間傳遞狀態。

HttpRequest.method

一個字符串,表示請求使用的HTTP 方法。必須使用大寫。例如:

if request.method == 'GET':

do_something()

elif request.method == 'POST':

do_something_else()

HttpRequest.path 一個字符串,表示請求的頁面的完整路徑,不包含域名。

HttpRequest.POST 一個類似於字典的對象,如果請求中包含表單數據,則包含HTTP POST 的所有參數。

HttpRequest.COOKIES 一個標準的Python 字典,包含所有的cookie。鍵和值都爲字符串。

HttpRequest.FILES 一個類似於字典的對象,包含所有的上傳文件。FILES 中的每個鍵爲<input type="file" name="" /> 中的name。

JsonResponse 對象

典型的用法如下:

from django.http import JsonResponse

response = JsonResponse({'foo': 'bar'})


文件上傳

當Django在處理文件上傳的時候,文件數據被保存在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'])


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章