django中GET与POST请求
django中GET与POST请求_纯洁的小魔鬼-CSDN博客
一.Get请求
view.py中定义:
from django.http import HttpResponse
从request中取值的两种形式:
request.GET.get("name")
request.GET["name"]
from django.http import HttpResponse
def hello(request):
name = request.GET.get("name")
message = request.GET["message"]
return HttpResponse("Hello " + name + " ! " + message)
urls.py文件中的添加路径
from django.conf.urls import url
from django.contrib import admin
from . import view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^hello/$', view.hello),
]
浏览器中发送请求:
http://127.0.0.1:8000/hello/?name=why&message=Today is my birthday!
输出:Hello why ! Today is my birthday!
二.post请求
1.form-data或x-www-form-urlencoded传参
从request中取值的两种形式:
request.POST.get("name")
request.POST["name"]
from django.http import HttpResponse
def hi(request):
name = request.POST.get("name")
message = request.POST["message"]
return HttpResponse("Hello " + name + " ! " + message)
urls.py文件中的添加路径
from django.conf.urls import url
from django.contrib import admin
from . import view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^hi/$', view.hi),
]
可以使用postman进行测试
2.JSON(application/json)格式传参
利用json模块的loads函数
from django.http import HttpResponse
import json
def test(request):
d = json.loads(request.body)
name = d["name"]
message = d["message"]
return HttpResponse("Hello " + name + " ! " + message)
urls.py文件中的添加路径
from django.conf.urls import url
from django.contrib import admin
from . import view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^test/$', view.test),
]
传参形式:
{
"name":"why",
"message":"Today is my birthday!"
}
使用postman进行测试:
————————————————
版权声明:本文为CSDN博主「纯洁的小魔鬼」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xyy1028/article/details/84981634