python中response.text_Sanic response text() 函数用法和示例
response.text() 功能:Sanic 返回純文本內容給瀏覽器。作為一個完整功能的web網站,一般是不會返回純文本內容的,特殊情況下可選擇使用本函數。
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
我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。
***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***
總結
以上是生活随笔為你收集整理的python中response.text_Sanic response text() 函数用法和示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python序列符号_初识Python(
- 下一篇: linux用命令行进行无线连接,linu