发送 post json 请求 Request

1
2
import requests
requests.post('http://localhost:8999', json={"hello": "data"})

上传文件 和 multpart/form-data

参考:

上传文件

用法:

  1. 单独设置文件内容

    1
    2
    
    files = {"myfile": open("file/path", 'rb')}
    requests.post(url, files=files)
  2. 设置(文件名,文件内容,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)
  3. 上传 str 作为文件内容

    1
    
    files = {'file': ('report.csv', r'some,data,to,send\nanother,row,to,send\n')}
  4. 大文件上传

同时上传文件 + 传递参数

  1. curl 例子:

    1
    2
    3
    4
    5
    6
    7
    
    curl -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'
  2. requests 例子:

    1
    2
    3
    4
    5
    
    requests.post('http://localhost:10030/', files=[
        ('files', open('/path/to/file.pdf', "rb")), # 上传文件
        ('files', open('/path/to/file_1.pdf', "rb")),
        ('containJson', (None, False)) # 普通参数
    ])
  3. 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)