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

veelion發表於2019-03-23

response.text() 功能:Sanic 返回純文字內容給瀏覽器。作為一個完整功能的web網站,一般是不會返回純文字內容的,特殊情況下可選擇使用本函式。

response.text() 函式

response.text() 語法

def text(
    body,
    status=200, headers=None,
    content_type="text/plain;
    charset=utf-8"
):

response.text() 引數

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

這裡面,body是必需的引數,可以通過傳入headers來自定義響應頭,其它引數不要修改。
比如,自定義響應頭headers:


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

response.text() 返回值

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

response.text() 例子

from sanic import Sanic
from sanic import response


app = Sanic()


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


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

通過curl來檢視text響應:

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

結果如下,可以看到我們自定義的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: text/plain; charset=utf-8

Welcom to 猿人學Python

猿人學banner宣傳圖

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

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

相關文章