您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:python中的post请求解读

51自学网 2025-02-05 12:14:59
  python
这篇教程python中的post请求解读写得很实用,希望能帮到您。

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 requestsurl = '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 adminfrom django.urls import path, re_path, includeurlpatterns = [    path('admin/', admin.site.urls),    # 将主路由和子路由绑定    path('', include('gp_app.urls')),]

子路由的配置

from django.urls import re_pathfrom . import viewsurlpatterns = [    # 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 renderfrom 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之后,控制台的结果

(4)data表单使用嵌套的数据结构如何处理

情况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 urlencodedata = {‘a': 1, ‘b': 2,‘c':‘测试'}data =urlencode(data)resp = reuquest.post(url=url,headers=headers,data=data)

2.multipart/form-data

  • multipart/form-data是常用来上传文件的表单
  • application/json
  • text/xml

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。


python中geopandas库安装出现各种问题的解决办法
Python自动检测requests所获得html文档的编码
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。