Sanic response raw() 函式用法和示例

veelion發表於2019-03-23

response.raw() 功能:Sanic 返回二進位制資料給瀏覽器。

Sanic response.raw() 函式

response.raw() 語法

def raw(
    body,
    status=200, headers=None,
    content_type="application/octet-stream;
):

response.raw() 引數

  • body:響應要返回的bytes字串,不是str
  • status:預設 http 狀態碼200,正常返回不要修改;
  • headers:自定義 http 響應頭;
  • content_type:純文字的content type,不要修改;

raw()text()非常像,不同的是,raw()傳入的body必須是bytes字串(即,str編碼後的結果)。這裡面,body是必需的引數,可以通過傳入headers來自定義響應頭,其它引數不要修改。
比如,自定義響應頭headers:


return raw('Welcom to 猿人學Python',
            headers={'X-Serverd-By': 'YuanRenXue Python'})

response.raw() 返回值

返回一個HTTPResponse類的例項。多數情況下,路由函式直接返回這個例項。當需要再進一步處理響應(比如,設定響應cookies)時,要把它賦值給一個變數。

response.raw() 例子

from sanic import Sanic
from sanic import response


app = Sanic()


@app.route('/raw')
async def raw(request):
    msg = 'Welcom to 猿人學Python'
    return response.raw(
        msg.encode('utf8'),
        headers={'X-Serverd-By': 'YuanRenXue Python'}
    )


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888)

注意:傳入的字串必須是編碼後的bytes

通過curl來檢視raw響應:

curl -i http://127.0.0.1:8888/raw

結果如下,可以看到我們自定義的headersX-Serverd-By: YuanRenXue Python


HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Content-Length: 25
Content-Type: application/octet-stream

Welcom to 猿人學Python

請注意Content-Type與其它響應函式的不同。

猿人學banner宣傳圖

我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。

***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***

相關文章