Python - Django - request 對象


request.method:

獲取請求的方法,例如 GET、POST 等

views.py:

from django.shortcuts import render, HttpResponse

# request 對象
def test(request):
    print(request.method)
    return render(request, "test.html")

訪問頁面

可以通過 request.method 查看請求方式

 

request.GET:

用來獲取 URL 里面的 GET 方式的參數

views.py:

from django.shortcuts import render, HttpResponse

# request 對象
def test(request):
    print(request.GET)  # 返回的是一個字典類型
    print(request.GET.get("id"))  # 通過 key 獲取相對應的 value
    return render(request, "test.html")

訪問:http://127.0.0.1:8000/test/?id=2&username=admin&password=123456

 

request.POST:

用來獲取 POST 提交過來的數據

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試頁面</title>
</head>
<body>

<p>測試頁面</p>

<form action="/test/" method="post">
    <input type="text" name="username" value="">
    <input type="submit" name="提交">
</form>

</body>
</html>

views.py:

from django.shortcuts import render, HttpResponse

# request 對象
def test(request):
    print(request.POST)  # 返回的是一個字典類型
    print(request.POST.get("username"))  # 通過 key 獲取相對應的 value
    return render(request, "test.html")

訪問網頁:

提交

 

request.body:

請求體,byte 類型,request.POST 的數據就是從 body 里提取的

views.py:

from django.shortcuts import render, HttpResponse

# request 對象
def test(request):
    print(request.body)
    return render(request, "test.html")

訪問網頁:

提交:

這兩串是 “提交” 的 URL 編碼

 

request.path_info:

獲取用戶請求的路徑,不包含域名和 URL 參數

from django.shortcuts import render, HttpResponse

# request 對象
def test(request):
    print(request.path_info)
    return render(request, "test.html")

訪問:http://127.0.0.1:8000/test/?id=2&username=admin

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM