簡體   English   中英

每當在 Flask 應用程序中請求 static 文件時,捕獲請求標頭

[英]Capture Request Headers whenever a static file is requested in Flask App

全部,

每當向端點發出請求時,我都能夠捕獲請求標頭,但我想知道在請求 static 文件時如何捕獲請求標頭。

例如,每當請求通過此端點獲取圖像時,我都可以將標頭寫入帶有時間戳的 .txt 文件,如下所示。

https://<host_name>/img

請求標頭示例:

============================
28/05/2020, 14:31:03
Request Headers: 
Host: <host_name>
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,kn;q=0.8
X-Request-Id: 00a79a7f-84eb-4fb3-b949-76254a93a001
X-Forwarded-For: 157.49.191.87
X-Forwarded-Proto: https
X-Forwarded-Port: 443
Via: 1.1 vegur
Connect-Time: 0
X-Request-Start: 1590676263802
Total-Route-Time: 0

============================

但是當有人像這樣直接訪問 static 對象時:

https://<host_name>/static/img/<img_name>.png

在沒有任何路由或視圖作為上述端點直接請求時,如何捕獲 static 對象的請求標頭?

目前,我正在使用 Flask 中的request.headers捕獲請求標頭。 我的 img 端點的 function 如下所示:

@app.route('/img')
def img_func():
    req_headers = request.headers
    dir = "static"
    full_path = os.path.join(dir, "logs")
    filename = full_path +'/request_headers_img.txt'

    if os.path.exists(filename):
        append_write = 'a'  # append if already exists
    else:
        append_write = 'w'  # make a new file if not

    now = datetime.datetime.now()
    date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
    app_logs = open(filename, append_write)
    app_logs.write("============================" + '\n')
    app_logs.write(date_time + '\n')
    app_logs.write("Request Headers: " + '\n' + str(req_headers))
    app_logs.write("============================"+ '\n')
    app_logs.close()

    fn = os.path.join(dir, "img") + '/<file_name>.png'

    return send_file(fn)

當我確實檢查了一些在線鏈接時,有人提到使用request.path('static')但不確定如何實現這一點並捕獲請求標頭。

One more thing which was mentioned there that the static files are being served from the webserver like Nginx or Apache , not from the flask app if static files are requested directly as I mentioned above. 如果是這樣,有沒有辦法在網絡服務器級別捕獲這些 static 請求標頭?

僅供參考:該應用程序是使用 Flask、Python 3 構建的,並使用 Heroku 使用來自 ZE301ADBCBB9F9DDEZ726 的 CI/CD 部署到 Heroku。

任何關於此的幫助,或者如果有人可以指出我可以閱讀和實施的資源,這將是非常有用的人。

提前致謝!

好的,所以我要回答

(a) 每當在 Flask 應用程序中請求 static 文件時,捕獲請求標頭?

@app.route("/static/<var1>/<var2>")
def test(var1,var2):
    print(request.headers)
    return "hehe"

讓我知道這是否適合您,並回答您問題的 (a) 部分

這是我正在尋找的更新代碼:

@app.route('/sta/<path:path>')
def getStaticFile(path):
    fn = str(path).split("/")[-1]
    file_type = str(fn).split(".")[-1]

    dir = "static"
    full_path = os.path.join(dir, "logs")
    if file_type == 'png':
        req_headers = request.headers
        filename = full_path + '/request_headers_img.txt'

        if os.path.exists(filename):
            append_write = 'a'  # append if already exists
        else:
            append_write = 'w'  # make a new file if not

        now = datetime.datetime.now()
        date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
        app_logs = open(filename, append_write)
        app_logs.write("============================" + '\n')
        app_logs.write(date_time + '\n')
        app_logs.write("Request Headers: " + '\n' + str(req_headers))
        app_logs.write("============================" + '\n')
        app_logs.close()
    return send_from_directory('static', path)

我應該使用<path:path>而不是<var1>/<var2> 謝謝,Akib 調查它!

暫無
暫無

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

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