预设response对象

在web开发中,我们大部分的请求返回的都是json字符串,html片段,或者纯text。框架为开发者提供了几个预设函数,方便开发者迅速开发。

from luya import response

response.json() #返回一个content-type为application/json的response对象

response.text() #返回一个content-type为"text/plain:charset=utf-8"的response对象

response.html() #返回一个content-type为""text/html; charset=utf-8""的response对象

我们每一个路由函数返回的对象都必须是一个response对象

from luya import Luya
from luya import response

app = Luya()

@app.route('/json')
async def rsp_json(request):
    return response.json({msg:'this is a json string'})


@app.route('/html')
async def rsp_html(request):
    return response.html('<h1>hello,world</h1>')

@app.route('/text')
async def rsp_html(request):
    return response.text('hello,world')



if __name__ == '__main__':
    app.run()

如果路由函数返回的不是一个response对象,那么就会抛出一个框架内部错误,返回给请求方(http status_code = 500)。

自定义response对象

框架同样提供给开发自定义response对象的能力.

from luya.response import HTTPResponse

@app.route('/custom')
async def rsp_html(request):
    rsp = HTTPResponse(status=200)
    return rsp
#HTTPResponse构造函数参数

status #http状态码
body  #返回的body
content_type # 返回的content_type,默认是text/plain
header #返回的header

results matching ""

    No results matching ""