python - Tornado中的`send_error`, `write_error`和`raise HTTPError`有什么区别?

查看:349
本文介绍了python - Tornado中的`send_error`, `write_error`和`raise HTTPError`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

RT,官方文档看的不是很懂:

RequestHandler.send_error(status_code=500, kwargs)**

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.


RequestHandler.write_error(status_code, kwargs)**

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the current exception for purposes of methods like sys.exc_info() or traceback.format_exc.

我理解的是send_error调用了write_error,所以写自定义错误页面的时候要自己实现write_error方法,抛出错误的时候使用send_error。那么又该在什么时候使用rasie tornado.web.HTTPError呢?

解决方案

HTTPError一般是用tornado访问某个url,然后这个url不存在,或者返回一个错误码的时候用到的。

from tornado.httpclient import HTTPClient, HTTPError
http_client = HTTPClient()
try:
    response = http_client.fetch(url, method='GET', request_timeout=120)
except HTTPError as http_error:
    print http_error
except Exception as e:
    print e
finally:
    http_client.close()

这篇关于python - Tornado中的`send_error`, `write_error`和`raise HTTPError`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆