python post请求
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
python post请求
post请求有4中编码方式
1.application/x-www-form-urlencoded
application/x-www-form-urlencoded是浏览器原生的form表单提交的数据会按照key1=val1&key2=val2的格式经过url转码然后传输
1发送post请求
我们除了可以直接编写代码发送post请求也可以使用postman来构造post请求
使用代码
import requests
url = 'https://www.xxxxxx.com/'
# 需要注意的是Content-Length参数如果没有data表单则不会随着请求被发送给服务端且使用fiddler抓包的过程中也无法看到data表单
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length':'<calculated when request is sent>'
}
data = {'a': 1, 'b': 2,'c':'测试'}
result = requests.post(url, headers=headers, data=data)
print(result.content.decode('utf-8'))
使用postman
2截获post请求使用fiddler
3接收post请求返回响应
使用django3的版本目录结构如下
settings的配置
主路由的配置
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
# 将主路由和子路由绑定
path('', include('gp_app.urls')),
]
子路由的配置
from django.urls import re_path
from . import views
urlpatterns = [
# name用于给视图命名可以通过reverse反向解析
re_path(r'try_get/', views.get, name='get请求'),
re_path(r'try_post', views.post, name='post请求')
]
views.py的配置
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def get(request):
if request.method == 'get':
print(request.GET.getlist('c'))
pass
return HttpResponse("ok")
def post(request):
if request.method == 'POST':
print("request.method:", request.method)
print("request.POST.getlist('a'):", request.POST.getlist('a'))
print("request.POST.getlist('b'):", request.POST.getlist('b'))
print("request.POST.getlist('c'):", request.POST.getlist('c'))
print("request.POST:", request.POST)
a = request.POST.get('a', 0)
c = request.POST.get('c', 0)
d = str({a: c}) # 需要注意的是如果要使用HttpResponse来返回响应参数需要是字符串d如果不转换成str返回的结果就是1
return HttpResponse(d)
运行django之后控制台的结果
4data表单使用嵌套的数据结构如何处理
情况1使用json_dumps
postData = {
'tid': 1'',
'data': [{'name': 'rqlx', 'value': '0', 'sword': 'attr'},{'name': 'rq1', 'value': '1', 'sword': 'attr'}],
'bindParam': 'true'
}
# 注意json.dumps转换成json格式或许也能写成
# data = json.dumps({'postData':{ 'tid': 1'', 'data': [{'name': 'rqlx', 'value': '0'},{'name': 'rq1', 'value': '1'}], 'bindParam': 'true'}})
# 将json.dumps放在外层
data = {
'postData':json.dumps(postData)
}
resp = requests.post(
url=url,
data=data,
headers=headers,
# cookies=dict_cookie, # cookie也可以用字典的形式写到headers类似于’Cookie':'xxxxxxxxxx'
timeout=240,
)
情况2使用url编码
有的时候表单提交时需要先进行url转码关键在于后端到底要接收什么类型的数据如果我们不知道后端能处理的数据有时就只能靠猜用不同的方法尝试将表单处理成能被后端解析的格式
from urllib.parse import urlencode
data = {‘a’: 1, ‘b’: 2,‘c’:‘测试’}
data =urlencode(data)
resp = reuquest.post(url=url,headers=headers,data=data)
2.multipart/form-data
multipart/form-data是常用来上传文件的表单