Skip to content

Instantly share code, notes, and snippets.

@zh4n7wm
Created May 4, 2019 09:14
Show Gist options
  • Select an option

  • Save zh4n7wm/437d8937f701984d129b822e7d4359f8 to your computer and use it in GitHub Desktop.

Select an option

Save zh4n7wm/437d8937f701984d129b822e7d4359f8 to your computer and use it in GitHub Desktop.
tornado web tips

记录 tornado web 开发 tips

提前终止 request 流程

tornado web 可以通过 self.write 调用多次,将数据发送到客户端,如果想提前终止,最容易想到的方法肯定是 return self.write。这会产生两个问题:

  • pylint 提醒 A function or a method has inconsistent return statements
  • 如果想写个帮助函数,比如:自定义异常处理,但调用它后就不希望程序再继续往下运行了,这时没法直接在帮助函数中终止流行流程,需要手动调用 return help_method
  • 如果帮助函数是做些检查,达到某个条件时就终止程序继续运行,否则,继续。就只能检查该函数的返回值,然后再对不同条件做不同处理。每个调用它的函数中都需要如此这般,非常麻烦

这时,我们可以通过 raise tornado.web.Finish() 让程序提前结束

举个🌰,help(tornado.web.Finish) 就能看到它

if self.current_user is None:
    self.set_status(401)
    self.set_header('WWW-Authenticate', 'Basic realm="something"')
    raise Finish()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment