溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

發(fā)布時(shí)間:2020-10-05 18:42:04 來源:腳本之家 閱讀:130 作者:Gaidy 欄目:開發(fā)技術(shù)

路由

路由可以定義在工程的目錄下(看你的需求),也可以定義在各個(gè)應(yīng)用中來保存應(yīng)用的路由,用主路文件urls中使用include()包含各個(gè)應(yīng)用的子路由的數(shù)據(jù)

路由的解析順序

Django接收到請(qǐng)求后,從主路由文件urlpatterns中的路由從上倒下順序查找,如果有include包含,則進(jìn)入子應(yīng)用的urls中的urlpatterns中查找(從上而下)

路由的結(jié)尾斜線

Django有/結(jié)尾路由,用戶不需要加/,就可以直接重定向到/結(jié)尾的路徑上

路由命名(可以避免不同應(yīng)用使用相同名字發(fā)生沖突)

如:

# 主路由
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反解析(子應(yīng)用的路由都需要命名)

注意點(diǎn):

  1. 對(duì)于未指明namespace的,reverse(路由name)
  2. 對(duì)于指明namespace的,reverse(命名空間namespace:路由name)

請(qǐng)求(POST,PUT,PATCH,DELETE)默認(rèn)開啟CSRF防護(hù)

post請(qǐng)求那些需要到postman測(cè)試工具里面測(cè)試

先把CSRF防護(hù)注釋掉

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

服務(wù)器傳遞參數(shù)的方式

URL:直接在URL中傳遞數(shù)據(jù)

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

請(qǐng)求體:在body中傳遞數(shù)據(jù),常見有表單,json,xml

請(qǐng)求頭:在http報(bào)文頭中

URL參數(shù)傳遞

未定義參數(shù)順序傳遞

子應(yīng)用的路由設(shè)置

urlpatterns = [
  # 這邊定義子應(yīng)用的路由
  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'),
]

定義視圖函數(shù)

# name,和age參數(shù)位置調(diào)換會(huì)影響下面的輸出結(jié)果
def parameter(request,name, age):

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

命名參數(shù)按照名字傳遞

子路由

urlpatterns = [
  # 這邊定義子應(yīng)用的路由
  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'),
]

視圖函數(shù)

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

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

查詢字符串(傳遞參數(shù))

注意:查詢字符串不區(qū)分請(qǐng)求方式,即假使客戶端進(jìn)行POST方式的請(qǐng)求,依然可以通過request.GET獲取請(qǐng)求中的查詢字符串?dāng)?shù)據(jù)。

子路由

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

視圖函數(shù)

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')

運(yùn)行(后面在加)

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

請(qǐng)求體(傳遞參數(shù))

表單類

路由設(shè)置

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

視圖函數(shù)

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')

運(yùn)行

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

非表單類

路由

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 無需執(zhí)行此步
  req_data = json.loads(json_str)
  print(req_data['a'])
  print(req_data['b'])
  return HttpResponse('OK')

運(yùn)行

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

請(qǐng)求頭(傳遞參數(shù))

可以通過request.META屬性獲取請(qǐng)求頭headers的數(shù)據(jù)

路由

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

視圖函數(shù)

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

運(yùn)行

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

常見的請(qǐng)求頭

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).

響應(yīng)

  1.  HttpResponse提供一系列子類
  2. HttpResponseRedirect 301
  3. HttpResponsePermanentRedirect 302
  4. HttpResponseNotModified 304
  5. HttpResponseBadRequest 400
  6. HttpResponseNotFound 404
  7. HttpResponseForbidden 403
  8. HttpResponseNotAllowed 405
  9. HttpResponseGone 410
  10. HttpResponseServerError 500

案例 # HttpResponse(content=響應(yīng)體,content_type=響應(yīng)數(shù)據(jù)類型,status=狀態(tài)碼)

# content:表示返回的內(nèi)容
# status_code:返回的HTTP響應(yīng)狀態(tài)碼
# content_type: 指定返回?cái)?shù)據(jù)的MIME類型
from django_http import HttpResponse

def index(request):
  return HttpResponse('歡迎來到Gaidy博客', status=202)

JsonResponse(返回的json數(shù)據(jù))

from django.http import JsonResponse

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

運(yùn)行結(jié)果

Django框架的使用教程路由請(qǐng)求響應(yīng)的方法

redirect重定向

from django.shortcuts import redirect

# django_test是路由的空間命名
def show(request):
  # 重定向
  return redirect(reverse('django_test:index'))

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI