response.html() 功能:Sanic 返回html文本内容给浏览器。一般在服务器端渲染网页的web应用返回的都是html文本,Sanic可借助jinja2实现html模板的渲染。
response.html() 语法
def html(body, status=200, headers=None):
response.html() 参数
- body:响应要返回的html文本字符串;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
这里面,body
是必需的参数,可以通过传入headers
来自定义响应头,其它参数不要修改。
自定义响应头headers:
return html('Welcom to 猿人学Python',
headers={'X-Serverd-By': 'YuanRenXue Python'})
response.html() 返回值
返回一个HTTPResponse
类的实例。多数情况下,路由函数直接返回这个实例。当需要再进一步处理响应(比如,设置响应cookies)时,要把它赋值给一个变量。
response.html() 例子
from sanic import Sanic
from sanic import response
app = Sanic()
@app.route('/html')
async def html(request):
return response.html(
'Welcom to 猿人学Python',
headers={'X-Serverd-By': 'YuanRenXue Python'}
)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
通过curl
来查看html响应:
curl -i http://127.0.0.1:8888/html
结果如下,可以看到我们自定义的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/html; charset=utf-8
Welcom to 猿人学Python

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...