Flask 請求內(nèi)容校驗(yàn)碼

2021-08-11 10:34 更新

許多代碼可以消耗請求數(shù)據(jù)并對其進(jìn)行預(yù)處理。例如最終出現(xiàn)在已讀取的請求對 象上的 JSON 數(shù)據(jù)、通過另外的代碼路徑出現(xiàn)的表單數(shù)據(jù)。當(dāng)你想要校驗(yàn)收到的 請求數(shù)據(jù)時(shí),這似乎帶來不便。而有時(shí)這對某些 API 是必要的。

幸運(yùn)的是,無論如何可以包裝輸入流來簡單地改變這種狀況。

下面的例子計(jì)算收到數(shù)據(jù)的 SHA1 校驗(yàn)碼,它從 WSGI 環(huán)境中讀取數(shù)據(jù)并把校驗(yàn) 碼存放到其中:

import hashlib

class ChecksumCalcStream(object):

    def __init__(self, stream):
        self._stream = stream
        self._hash = hashlib.sha1()

    def read(self, bytes):
        rv = self._stream.read(bytes)
        self._hash.update(rv)
        return rv

    def readline(self, size_hint):
        rv = self._stream.readline(size_hint)
        self._hash.update(rv)
        return rv

def generate_checksum(request):
    env = request.environ
    stream = ChecksumCalcStream(env['wsgi.input'])
    env['wsgi.input'] = stream
    return stream._hash

要使用這段代碼,所有你需要做的就是在請求消耗數(shù)據(jù)之前調(diào)用計(jì)算流。(例如: 小心訪問 request.form 或其它此類的東西。例如,應(yīng)注意避免 before_request_handlers 訪問它)。

用法示例:

@app.route('/special-api', methods=['POST'])
def special_api():
    hash = generate_checksum(request)
    # Accessing this parses the input stream
    files = request.files
    # At this point the hash is fully constructed.
    checksum = hash.hexdigest()
    return 'Hash was: %s' % checksum
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號