requests ---- python requests library
文章目录
教程
- requests官方教程
- curl 转换工具: Convert curl commands to code
发送 post json 请求 Request
| |
上传文件 和 multpart/form-data
参考:
- POST a Multipart-Encoded File
- How to send a "multipart/form-data" with requests in python? - Stack Overflow
上传文件
用法:
单独设置文件内容
1 2files = {"myfile": open("file/path", 'rb')} requests.post(url, files=files)设置(文件名,文件内容,content-type, 额外 header 信息)
1 2 3 4 5 6 7# 通过 dict 传输 files = {"myfile": ("mydoc.xlsx", open("file/path", 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} # 通过 list[tuple], 支持多个 文件传输, 一个 form field `file` 被传入多个文件, file 是字段名,可以改变比如 files, myfiles files = [("file", ("mydoc.xlsx", open("file/path", 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})) ("file", ("mydoc.xlsx", open("file/path", 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})) ] requests.post(url, files=files)上传 str 作为文件内容
1files = {'file': ('report.csv', r'some,data,to,send\nanother,row,to,send\n')}大文件上传
同时上传文件 + 传递参数
curl 例子:
1 2 3 4 5 6 7curl -X 'POST' \ 'http://localhost:10030/' \ -H 'accept: application/json' \ -H 'Content-Type: multipart/form-data' \ -F 'files=@/path/my_demo.pdf;type=application/pdf' \ -F 'files=@/path/my_demo_01.pdf;type=application/pdf' \ -F 'containJson=false'requests 例子:
1 2 3 4 5requests.post('http://localhost:10030/', files=[ ('files', open('/path/to/file.pdf', "rb")), # 上传文件 ('files', open('/path/to/file_1.pdf', "rb")), ('containJson', (None, False)) # 普通参数 ])fastapi server 例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19# -*- coding: utf-8; -*- from typing import Annotated from fastapi import FastAPI, UploadFile, Request, Response, Form app = FastAPI() @app.post("/") def upload(files: list[UploadFile], containJson: Annotated[bool, Form()]): for file in files: print(file.filename, file.size) print(f"{containJson = }") return {"containJson": containJson} if __name__ == "__main__": import uvicorn uvicorn.run(app, port=10030)
文章作者
上次更新 2025-06-20 (811ee6f)