• 【Python】接口自动化 - requests请求上传文件的接口


    场景

    使用requests实现文件上传的接口自动化。
    接口的请求类型为:Content-Type:multipart/form-data;
    接口入参存在一个数据类型为file的参数。如下:
    在这里插入图片描述

    requests基础知识

    • 4个requests传参类型:
      parmas: 传递查询字符串参数(常用于get请求)
      data: 传递表单类型的参数(参数类型为:Content-Type:application/x-www-form-urlencoded)
      json: 传递json类型的参数(参数类型为:Content-Type:application/json)
      files: 用于上传文件(参数类型: content-type:multipart/form-data;)

    上传文件的的接口参数的类型为content-type:multipart/form-data,那么我们使用requests来发送请求的时候,接口中文件上传的参数需要使用files来传递。files参数格式如下:

    files = {
    	"file": ("test.xlsx", open("D:\\test.xlsx", "rb"), "application/octet-stream")
    }
    # 或者
    files = {
    	"pic": ("test.gif", open("D:\\test.gif", "rb"), "images/gif")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    注意:

    1. files为字典类型数据,上传的文件为键值对的形式:入参的参数名作为键,参数值是一个元组,内容为以下格式(文件名,打开并读取文件,文件的content-tpye类型)
    2. 除了上传的文件,接口其他参数不能放入files中,使用data传递即可。

    解决方案

    完整的请求代码如下:

    import requests
    # 请求url
    url = "https://127.0.0.1/upload"
    # 请求头
    headers = {
        "Authorization": "bearer abcde"
    }
    # 上传文件的参数
    files = {
            "file": ("test.xlsx", open("D:\\test.xlsx", "rb"), "application/octet-stream")
        }
    # 其他参数
    data = {
        "id": "1585171115599216642"
    }
    # 发送请求
    response = requests.post(url=url, headers=headers, files=files, data=data)
    # 打印结果
    print(response.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    运行以上代码,结果如下:
    {‘datas’: True, ‘code’: 200, ‘msg’: ‘SUCCESS’}

  • 相关阅读:
    mysql之update语句锁分析
    从0开始学习JavaScript--JavaScript 异步编程
    『手撕Vue-CLI』拷贝模板
    SQL数据库设计 用语言查询数据
    软件测试学习(三)易用性测试、测试文档、软件安全性测试、网站测试
    计算机图像处理-高斯滤波
    修改WPF程序集名称报错
    linux内核的reciprocal_value结构体
    Hadoop----Azkaban的使用与一些报错问题的解决
    【C语言刷LeetCode】1583. 统计不开心的朋友(M)
  • 原文地址:https://blog.csdn.net/weixin_49026134/article/details/127542929