如何自定义 boundary 字符串?

解读

在国内一线互联网公司的面试中,这道题常被用来区分“只会调接口”与“真正读过源码”的候选人。
面试官真正想听的是:

  1. 你知道 multipart/form-data 报文结构里 boundary 的作用;
  2. 你明白 Requests 默认用 uuid.uuid4().hex 生成随机串,但在对接 老旧 Java 网关、企业微信文件上传、银行存管接口 时,对方会要求固定且可预知的 boundary;
  3. 你能给出 不改动 Requests 源码 的前提下,把自定义 boundary 传进去的两种正规做法,并说出各自的副作用与性能差异;
  4. 你能指出 Requests 4.3.0 之后 内部如何把 boundary 写进 headers 与 body,以及为什么手动改 headers 会失效;
  5. 如果追问“怎么让 boundary 全局生效”,你能聊到 Session 级钩子 或自定义 MultipartEncoder 的子类化方案,而不是硬编码 monkey-patch。

知识点

  • multipart/form-data 报文规范:boundary 是分隔符,必须以 -- 开头且不在正文出现;
  • requests.models.RequestEncodingMixin._encode_files 内部流程:先构造 RequestField 列表 → 调 urllib3.filepost.encode_multipart_formdata → 返回 (body, content_type);
  • requests 4.3.0+ 把 boundary 生成推迟到 encode_multipart_formdata,因此 手动设置 headers['Content-Type'] 会被覆盖;
  • requests_toolbelt.MultipartEncoder 允许显式传 boundary=xxx,与 Session 的 prepare_request 钩子结合可做到 零入侵;
  • 企业内网代理抓包场景下,固定 boundary 能让 Diff 工具 忽略边界差异,方便回归比对;
  • 性能陷阱:自定义过长的 boundary 会 每请求增加几十字节流量,在高并发压测里可能被 SLB 日志计费 放大成额外成本。

答案

给出两种生产环境验证过的写法,按场景选择:

  1. 单次请求级(推荐,无副作用)
from requests_toolbelt import MultipartEncoder
import requests

boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'  # 满足对方正则
fields = {
    'file': ('test.xlsx', open('test.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
    'merchantId': '1001'
}
m = MultipartEncoder(fields=fields, boundary=boundary)

headers = {'Content-Type': m.content_type}
resp = requests.post('https://api.xxx.com/upload', data=m, headers=headers)
  1. Session 级全局生效(适合压测脚本)
import requests
from requests_toolbelt import MultipartEncoder

class FixedBoundarySession(requests.Session):
    def __init__(self, boundary):
        super().__init__()
        self.boundary = boundary

    def prepare_request(self, request):
        # 只拦截含文件的请求
        if request.files:
            enc = MultipartEncoder(
                fields=dict(request.files, **(request.data or {})),
                boundary=self.boundary
            )
            request.data = enc
            request.headers['Content-Type'] = enc.content_type
            request.files = None  # 必须置空,防止内部再走默认编码
        return super().prepare_request(request)

s = FixedBoundarySession('----MyCompanyBoundary2023')
s.post('https://api.xxx.com/upload', files={'file': open('f.xlsx', 'rb')})

注意:

  • 不要直接 headers={'Content-Type': 'multipart/form-data; boundary=xxx'} 然后 files=...,Requests 会 丢弃你给的 boundary 并重新生成;
  • boundary 长度 38 字节以内 最保险,避免对方 Nginx 默认 70 字节截断;
  • 如果接口同时校验 Content-Length,用 MultipartEncoder 后务必 禁用压缩,防止 Transfer-Encoding: chunked 导致对端验签失败。

拓展思考

  1. 如果面试官继续问“不想引入 requests_toolbelt 怎么办?”
    可答:继承 urllib3.filepost.encode_multipart_formdata,把 boundary 参数暴露出来,然后在 Session.prepare_request 里把 request.body 提前算好并 强制禁用文件流(files=None),实现 零依赖。但要承担 内存翻倍 的风险,不适合 200 MB 大文件。

  2. 若追问“高并发场景下固定 boundary 会不会导致缓存冲突?”
    可答:边界串只出现在 HTTP 载荷,不会参与 CDN 缓存键 计算;但部分 银行网关 会把整个正文做 MD5 校验,此时固定 boundary 反而能命中 白名单缓存,降低 TPS 抖动。

  3. 面试官最后可能让你“抓包证明”。
    准备一句:“我会用 mitmproxy -k --set keep_host_header=true 启动代理,在 Wireshark 过滤器 http.content_type contains "boundary=----MyCompanyBoundary2023" 里直接能看到,无需 root 权限 即可向面试官现场演示。”