美文网首页django
Django-04 GET和POST

Django-04 GET和POST

作者: JuliusL | 来源:发表于2021-07-09 22:55 被阅读0次
  • 无论是GET还是POST,统一由视图函数接收请求,通过判断request.method区分具体的请求动作
  • 样例:
if reuqest.method == 'GET':
  处理GET请求时的业务逻辑
elif requset.method == 'POST':
  处理POST请求的业务逻辑
else:
  其他请求业务逻辑

1,GET处理

  • GET请求动作吗,一般用于向服务器获取数据
  • 能够产生GET请求的场景
    • 浏览器地址栏中输入URL,回车后
    • <a href="地址?参数=值&参数=值">
    • form表单中的method为get
  • GET请求方法中,如果有数据需要传递给服务器,通常会用查询字符串(Query String)传递【注意:不要传递敏感数据】
  • URL格式:xxx?参数1=值1&参数名2=值2...
  • 服务器端接收参数:
def test_get_post(request):
    if request.method == 'GET':
        print(request.GET)
        print(request.GET.get('c','no c'))
        print(request.GET.getlist('a'))
        pass
    elif request.method == 'POST':
        pass
    else:
        pass
    return HttpResponse('test post get')

打印:

<QueryDict: {'a': ['1', '2', '3']}>
no c
['1', '2', '3']

2,POST处理

  • POST请求动作,一般用于向服务器提交大量/隐私数据
  • 使用post方式接收客户端数据:
POST_FORM = '''
<form method='post' action="/test_get_post">
  用户名:<input type="text" name="username">
  <input type='submit' value='登录'>
</form>
'''

def test_get_post(request):
    if request.method == 'GET':
        print(request.GET)
        print(request.GET.get('c','no c'))
        print(request.GET.getlist('a'))
        return HttpResponse(POST_FORM)
    elif request.method == 'POST':
        print('username is ',request.POST['username'])
        return HttpResponse('post is ok')
    else:
        pass
    return HttpResponse('test post get')
取消csrf验证
  • 取消csrf验证,否则Django将会拒绝客户端发来的POST请求,报403响应
  • 禁止掉settings.py中MIDDLEWARE中的CsrfViewsMiddleWare的中间件
MIDDLEWARE=[
  ...
    # 'django.middleware.csrf.CsrfViewMiddleware',
  ...
]

相关文章

  • Django-04 GET和POST

    无论是GET还是POST,统一由视图函数接收请求,通过判断request.method区分具体的请求动作 样例: ...

  • iOS请求方法和网络安全

    GET和POST请求 GET和POST请求简介 GET请求模拟登陆 POST请求模拟登陆 GET和POST的对比 ...

  • iOS请求方法和网络安全

    GET和POST请求GET和POST请求简介GET请求模拟登陆POST请求模拟登陆GET和POST的对比保存用户信...

  • HTTP

    get和post请求的区别 GET参数通过URL传递,POST放在Request body中。GET比POST更不...

  • post And get

    post And get post 与 get 请求的区别: 相同点:post和get都属于tcp协议传输。 po...

  • http协议,tcp/udp汇总

    GET和POST请求方式的区别? get获取数据,post发送数据 get拼接URL后面,post参数放在body...

  • API Test-基础知识

    1、接口测试的类型:get/post/delete/put 2、post和get的区别: a、get参数写在...

  • HTTP post和get请求的实现

    本文使用HttpClient包实现了HTTP的post和get请求。 · POST · GET

  • ajax 请求的时候 get 和 post 方式的区别?

    get和post的区别 get请求不安全,post安全 get请求数据有限制,post无限制 get请求参数会在u...

  • 实现异步请求的方法

    原生ajax写法: 请求方式:get,post,head,delete,get和post的区别 get将请求的参数...

网友评论

    本文标题:Django-04 GET和POST

    本文链接:https://www.haomeiwen.com/subject/norqpltx.html