django獲取請求引數

2022-07-03 22:48:22 字數 3545 閱讀 8215

需求:假設使用者訪問127.0.0.1/user/1/2,你想獲取1,2。應該怎麼操作呢?

(1)未命名引數(位置引數)

#

在專案下的urls.py下增加設定:

url(r'

^user/(\d+)/(\d+)$

',views.index)

#在user.views的index檢視中:

def index(request,a,b): #

接受的引數按順序的

獲得資料 %s %s

"%(a,b))

(2)命名引數(關鍵字引數)

#

在專案下的urls.py下增加設定:

url(r'

^user/(?p\d+)/(?p\d+)$

',views.index)

#在user.views的index檢視中:

def index(request,id,category): #

接受的引數可以不用按順序的

獲得資料 %s %s

"%(category,id))

輸出結果均是  獲得資料 1 2

需求:獲取127.0.0.1:8000/user?id=1&pid=99的查詢字串的值

#

在專案下的urls.py下增加設定:

url(r'

^user/$

',views.index)

#在user.views的index檢視中:

defindex(request):

id = request.get.get("id"

) pid = request.get.get("

pid"

)

獲得資料 %s %s

"%(id,pid))

注意:查詢字串的獲取與請求方式無關:不管是get還是post請求,都可以通過request.get屬性來獲取!!!

用postman傳送乙個表單請求。

def

index(request):

id = request.post.get("id"

) pid = request.post.get("

pid"

)

獲得資料 %s %s

"%(id,pid))

注意:request.post只能用來獲取post方式的請求體表單資料!

4.獲取非表單型別

def

index(request):

json_str =request.body

json_str = json_str.decode()#python3.6及以上不用這一句**

dict_data =json.loads(json_str)# loads把str轉換為dict,dumps把dict轉換為strid = dict_data.get("id"

) pid = dict_data.get("

pid"

)

獲得資料 %s %s

"%(id,pid))

常見的請求頭如下:

獲取請求頭內容的用meta

示例:

def

index(request):

ip = request.meta.get("

remote_addr")

你的ip位址是%s

"%ip)

用postman增加乙個自定義的請求頭,key=id,value=1。那麼應該怎麼取呢?

**如下:

你的id:%s

"%id)

注意:獲取自定義的請求頭屬性值時,需要新增字首http_並轉成大寫,作為鍵來獲取值

附錄(獲取各種請求引數的方法):

attribute

description

path

請求頁面的全路徑,不包括網域名稱埠引數。例如:/users/index

method

乙個全大寫的字串,表示請求中使用的http方法,常用值:getpostdeleteput等。以下三種為get請求:

user

get類似字典的querydict物件,包含url中所有的查詢字串引數

post

類似字典的querydict物件,包含post請求的所有鍵值對引數(表單資料)

body

獲取原始的請求體資料,獲取到的資料為bytes型別

files

乙個類似於字典的物件,包含所有的上傳檔案

meta

python字典型別,封裝了請求頭headers中的資料

-remote_addr– 客戶端的ip位址 

-request_method— 乙個字串,例如"get" 或"post

-content_type– 請求的正文的mime 型別

注意:對於使用者新增到請求頭中的鍵值,django會給鍵加上字首http_再轉換成大寫,再把鍵值儲存到request.meta中 

cookies

乙個標準的python字典,包含所有的cookies, 鍵和值都是字串

session

可讀可寫的類似字典的物件:django.contrib.sessions.backends.db.sessionstore

django提供了session模組,預設就會開啟用來儲存session資料

django獲取引數

獲取請求中所有的引數 def vue get request print request.get request.get dict data response data print 得到的get引數 dict data jsonify返回乙個json格式的資料 這裡也可以改寫成對資料庫的增刪改查後,...

獲取請求引數資訊

system.out.println 瀏覽器基本資訊 request.getheader user agent system.out.println 客戶端系統名稱 system.getproperty os.name system.out.println 客戶端系統版本 system.getpro...

openresty獲取請求引數

ngx.var.arg xx與ngx.req.get uri args xx 兩者都是為了獲取請求uri中的引數,例如 strider 1 為了獲取輸入引數strider,以下兩種方法都可以 local strider ngx.var.arg strider local strider ngx.re...