当前位置:   article > 正文

django中GET与POST请求_django中获取post和get请求中参数名为’name’值的语句是:

django中获取post和get请求中参数名为’name’值的语句是:

一.Get请求

view.py中定义:

from django.http import HttpResponse

从request中取值的两种形式:
request.GET.get("name")
request.GET["name"]

  1. from django.http import HttpResponse
  2. def hello(request):
  3. name = request.GET.get("name")
  4. message = request.GET["message"]
  5. return HttpResponse("Hello " + name + " ! " + message)

urls.py文件中的添加路径:

  1. from django.conf.urls import url
  2. from django.contrib import admin
  3. from . import view
  4. urlpatterns = [
  5. url(r'^admin/', admin.site.urls),
  6. url('^hello/$', view.hello),
  7. ]

浏览器中发送请求:

  1. http://127.0.0.1:8000/hello/?name=why&message=Today is my birthday!
  2. 输出:Hello why ! Today is my birthday!

二.post请求

1.form-data或x-www-form-urlencoded传参

从request中取值的两种形式:
request.POST.get("name")
request.POST["name"]

  1. from django.http import HttpResponse
  2. def hi(request):
  3. name = request.POST.get("name")
  4. message = request.POST["message"]
  5. return HttpResponse("Hello " + name + " ! " + message)

urls.py文件中的添加路径

  1. from django.conf.urls import url
  2. from django.contrib import admin
  3. from . import view
  4. urlpatterns = [
  5. url(r'^admin/', admin.site.urls),
  6. url('^hi/$', view.hi),
  7. ]

可以使用postman进行测试

2.JSON(application/json)格式传参

利用json模块的loads函数

  1. from django.http import HttpResponse
  2. import json
  3. def test(request):
  4. d = json.loads(request.body)
  5. name = d["name"]
  6. message = d["message"]
  7. return HttpResponse("Hello " + name + " ! " + message)

urls.py文件中的添加路径

  1. from django.conf.urls import url
  2. from django.contrib import admin
  3. from . import view
  4. urlpatterns = [
  5. url(r'^admin/', admin.site.urls),
  6. url('^test/$', view.test),
  7. ]

传参形式:

  1. {
  2. "name":"why",
  3. "message":"Today is my birthday!"
  4. }

使用postman进行测试:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/309927
推荐阅读
相关标签
  

闽ICP备14008679号