重定向

原理

正常返回的页面Status Code一般为200 OK,而重定向一般是返回302 Found的Status Code,再加上表示Location的Header。

方法

要将用户重定向到另一个页面,只需抛出HTTPFound,其location参数设置为新页面的绝对URL或相对URL。

例子

from lessweb import Bridge, get_mapping

@get_mapping('/')
async def hello():
    return {'message': 'Hello, world!'}

@get_mapping('/go-home')
async def go_home():
    raise web.HTTPFound(location='/')

def main():
    bridge = Bridge()
    bridge.add_route(hello)
    bridge.add_route(go_home)
    bridge.run_app()

请求:curl -L "http://localhost:8080/go-home"
返回:{"message":"Hello, world!"}