Python中通过requests模块发送POST请求.

2023-11-15

博客核心内容:


1、Python中通过requests模块发送POST请求.


我们通常情况下提交数据一般有两种方式:Ajax和Form表单的方式
如果request.post里面没有值,我们就到request.body里面去拿


代码示例:
服务端:

from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt,csrf_protect
# Create your views here.


#通过装饰器避免了csrf_token攻击
@csrf_exempt
def asset(request):
    """
    我们通常情况下提交数据一般有两种方式:Ajax和Form表单的方式
    """
    if request.method == 'GET':
        return HttpResponse('GET 收到...')
    else:
        print(request.POST)
        # print(request.body)
        """
        <QueryDict: {'salary': ['2000'], 
                     'username': ['Angela'], 
                     'password': ['123456']}
        >
        注意:如果request.post里面没有值,我们就到request.body里面去拿
        b'{"password": "123456", "username": "Angela", "salary": 2000}'
        """
        return HttpResponse('POST 收到...')

客户端:

#!/usr/bin/python
# -*- coding:utf-8 -*-

import requests

"""
通过requests可以向某个地址发送请求
"""

"""
response = requests.get('http://127.0.0.1:8000/asset.html')
# 通过get请求返回的文本值
print(response.text)
"""


# post发送的数据
postData = {
    'username':'Angela',
    'password':'123456',
    'salary':2000,
}

# 对于我们工作中的自己人,我们一般会使用别的验证,而不是csrf_token验证
response = requests.post('http://127.0.0.1:8000/asset.html',data=postData)
# 通过get请求返回的文本值
print(response.text)

效果图:
这里写图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中通过requests模块发送POST请求. 的相关文章

随机推荐