You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI中获取合规的HTTP TRACE响应?

在FastAPI中实现合规的HTTP TRACE响应

默认使用@app.trace定义的端点返回的响应不符合HTTP TRACE规范,规范要求响应体回显完整的请求起始行和请求头,且Content-Type为message/http。以下是实现合规响应的代码:

from fastapi import FastAPI, Request
from starlette.responses import Response

app = FastAPI()

@app.trace("/")
async def trace_endpoint(request: Request):
    # 构造请求行
    request_line = f"TRACE {request.url.path} HTTP/1.1\r\n"
    # 拼接所有请求头
    headers_str = "\r\n".join([f"{key}: {value}" for key, value in request.headers.items()])
    # 组合完整的响应内容(遵循message/http格式)
    response_content = f"{request_line}{headers_str}\r\n\r\n"
    
    return Response(
        content=response_content,
        status_code=200,
        media_type="message/http"
    )

验证效果

执行curl -v -X TRACE http://127.0.0.1:8000,会得到符合规范的响应:

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< date: Sat, 03 Sep 2022 15:52:55 GMT
< server: uvicorn
< content-length: xxx
< content-type: message/http
< 
TRACE / HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: curl/7.68.0
Accept: */*

关键说明

  • HTTP TRACE规范(RFC 7231)要求响应体必须是请求的完整副本,格式为message/http
  • 通过Request对象可以获取请求路径、请求头等原始信息,手动构造符合要求的响应内容
  • 使用starlette.responses.Response直接返回自定义内容,确保media_type设置为message/http

内容的提问来源于stack exchange,提问作者amirbahador

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:03:31