簡體   English   中英

如何在 fastapi 中獲得正確的 http 跟蹤響應?

[英]how get proper http trace response in fastapi?

這是我的代碼:

from fastapi import FastAPI

app = FastAPI()

@app.trace("/")
def test_trace():
    ...

這是響應: 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: 4
< content-type: application/json
< 
* Connection #0 to host 127.0.0.1 left intact

但我想要這樣的東西,其中包含TRACE header

< HTTP/1.1 200 OK
< date: Sat, 03 Sep 2022 15:52:55 GMT
< server: uvicorn
< content-length: 4
< content-type: application/json

< TRACE / HTTP/1.1
< Host: www.ssfkz.si
< User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0

通過使用響應 object,可以自定義標題(以及幾乎所有感興趣的細節)。

from fastapi import FastAPI, Response

app = FastAPI()

@app.trace("/")
def test_trace(response: Response):
    response.headers["TRACE"] = "HTTP/1.1"
    response.status_code = 200
    ...
    return {}

在詢問 SO 之前,請務必閱讀(和/或搜索)官方文檔( https://fastapi.tiangolo.com/advanced/response-headers/ )。

編輯

盡管 OP 提到設置TRACE “標頭”,但正式地,此 HTTP 方法的實現並未提及設置此類標頭,而是准確返回在跟蹤請求中收到的內容。

可以通過使用以下方法來實現近似行為:

@app.trace("/")
def test_trace(request: Request, response: Response):
    for k,v in request.headers.items():
        response.headers[k] = v
    # repeat for every property that should be echo-ed
    response.headers["Content-Type"] = "message/http" # RFC 7231
    response.status_code = 200 # RFC 7231
    return {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM