Django框架的使用教程--路由-請求-響應[四]

路由

路由能夠定義在工程的目錄下(看你的需求),也能夠定義在各個應用中來保存應用的路由,用主路文件urls中使用include()包含各個應用的子路由的數據python

路由的解析順序

Django接收到請求後,從主路由文件urlpatterns中的路由從上倒下順序查找,若是有include包含,則進入子應用的urls中的urlpatterns中查找(從上而下)django

路由的結尾斜線

Django有/結尾路由,用戶不須要加/,就能夠直接重定向到/結尾的路徑上json

路由命名(能夠避免不一樣應用使用相同名字發生衝突)

如:服務器

# 主路由
from
django.conf.urls import url,include from django.contrib import admin import django_test.urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/',include(django_test.urls ,namespace='users')) ]

reverser反解析(子應用的路由都須要命名)

注意點:函數

  • 對於未指明namespace的,reverse(路由name)
  • 對於指明namespace的,reverse(命名空間namespace:路由name)
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.urls import reverse


def index(request):

    return HttpResponse('歡迎來到Gaidy博客')


def show(request):
    url = reverse('users:index')
    print(url)
    return HttpResponse('OK')

請求(POST,PUT,PATCH,DELETE)默認開啓CSRF防禦

post請求那些須要到postman測試工具裏面測試工具

先把CSRF防禦註釋掉post

向服務器傳遞參數的方式

URL:直接在URL中傳遞數據測試

查詢字符串:key1=value1&key2=value2;url

請求體:在body中傳遞數據,常見有表單,json,xmlspa

請求頭:在http報文頭中

URL參數傳遞

未定義參數順序傳遞

子應用的路由設置

urlpatterns = [
    # 這邊定義子應用的路由
    url(r'^index/$',views.index,name='index'),
    url(r'^show/$',views.show,name='show'),
    url(r'^parameter/([a-z]+)/(\d{4})$',views.parameter,name='parameter'),
]

定義視圖函數

# name,和age參數位置調換會影響下面的輸出結果
def parameter(request,name, age):

    print('age=%s'%age)
    print('name=%s' % name)
    return HttpResponse('OK')

命名參數按照名字傳遞

子路由

urlpatterns = [
    # 這邊定義子應用的路由
    url(r'^index/$',views.index,name='index'),
    url(r'^show/$',views.show,name='show'),
    url(r'^parameter/(?P<name>[a-z]+)/(?P<age>\d{4})$',views.parameter,name='parameter'),
]

視圖函數

# age 和name位置改變值不變
def parameter(request,age, name):

    print('age=%s'%age)
    print('name=%s' % name)
    return HttpResponse('OK')

查詢字符串(傳遞參數)

注意:查詢字符串不區分請求方式,即假使客戶端進行POST方式的請求,依然能夠經過request.GET獲取請求中的查詢字符串數據。

子路由

url(r'^qust/$',views.qust),

視圖函數

def qust(request):
    a = request.GET.get('a')
    b = request.GET.get('b')
    alist = request.GET.getlist('a')
    print(a)  # 3
    print(b)  # 2
    print(alist)  # ['1', '3']
    return HttpResponse('OK')

運行(後面在加)

請求體(傳遞參數)

表單類

 路由設置

 url(r'^get_form/$', views.get_form)

視圖函數

def get_form(request):
    name = request.POST.get('name')
    age = request.POST.get('age')
    alist = request.POST.getlist('name')
    print(name)
    print(age)
    print(alist)
    return HttpResponse('OK')

運行

非表單類

 路由

url(r'^get_body_json/$', views.get_body_json),

視圖

def get_body_json(request):
    json_str = request.body
    json_str = json_str.decode()  # python3.6 無需執行此步
    req_data = json.loads(json_str)
    print(req_data['a'])
    print(req_data['b'])
    return HttpResponse('OK')

運行

請求頭(傳遞參數)

能夠經過request.META屬性獲取請求頭headers的數據

路由

url(r'^get_head/$', views.get_head)

視圖函數

def get_head(request):
    print(request.META['CONTENT_TYPE'])
    return HttpResponse('OK')

運行

常見的請求頭

  • CONTENT_LENGTH – The length of the request body (as a string).

  • CONTENT_TYPE – The MIME type of the request body.

  • HTTP_ACCEPT – Acceptable content types for the response.

  • HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.

  • HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.

  • HTTP_HOST – The HTTP Host header sent by the client.

  • HTTP_REFERER – The referring page, if any.

  • HTTP_USER_AGENT – The client’s user-agent string.

  • QUERY_STRING – The query string, as a single (unparsed) string.

  • REMOTE_ADDR – The IP address of the client.

  • REMOTE_HOST – The hostname of the client.

  • REMOTE_USER – The user authenticated by the Web server, if any.

  • REQUEST_METHOD – A string such as "GET" or "POST".

  • SERVER_NAME – The hostname of the server.

  • SERVER_PORT – The port of the server (as a string).

 響應

HttpResponse提供一系列子類

  • HttpResponseRedirect 301
  • HttpResponsePermanentRedirect 302
  • HttpResponseNotModified 304
  • HttpResponseBadRequest 400
  • HttpResponseNotFound 404
  • HttpResponseForbidden 403
  • HttpResponseNotAllowed 405
  • HttpResponseGone 410
  • HttpResponseServerError 500

案例# HttpResponse(content=響應體,content_type=響應數據類型,status=狀態碼)

# content:表示返回的內容 # status_code:返回的HTTP響應狀態碼 # content_type: 指定返回數據的MIME類型
from django_http import HttpResponse
def index(request): return HttpResponse('歡迎來到Gaidy博客', status=202)

 

JsonResponse(返回的json數據)

from django.http import JsonResponse

def index(request):
    return JsonResponse({'name': 'gaidy', 'age': '25'})

運行結果

redirect重定向

from django.shortcuts import redirect

# django_test是路由的空間命名
def show(request):
    # 重定向
    return redirect(reverse('django_test:index'))
相關文章
相關標籤/搜索