我使用 Tornado 创建了一个适用于同步方法的登录页面。现在我想将其设为异步。那么我应该对以下代码进行哪些更改:
import tornado.ioloop
import tornado.web
import http
import time
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class MainHandler(BaseHandler):
def get(self):
if not self.current_user:
self.redirect("/login")
return
name = tornado.escape.xhtml_escape(self.current_user)
self.write('<html>'
'<head> '
'<title>WELCOME </title>'
'</head>'
'<body style="background:orange;"'
'<div align="center">'
'<div style="margin-top:200px;margin-bottom:10px;">'
'<span style="width:500px;color:black;font-size:30px;font-weight:bold;">WELCOME </span>'
'</div>'
'<div style="margin-bottom:5px;">'"Hello, " + name)
class LoginHandler(BaseHandler):
def get(self):
self.write('<html><body><form action="/login" method="post">'
'<div><span style="width:100px;;height: 500px;color:black;font-size:60;font-weight:bold;">'
'LOGIN'
'<div><span style="width:100px;;height: 500px;color:purple;font-size:30;font-weight:bold;">'
'NAME <input type="text" name="name">'
'<div><span style="width:100px;height: 500px;color:purple;font-size:30;font-weight:bold;">PASSWORD</span><input style="width:150px;" type="password" name="password" id="password" value="">'
'</div>'
'<input type="submit" value="Sign in">'
'</form></body></html>')
def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
time.sleep(10)
self.redirect("/")
application = tornado.web.Application([
(r"/", MainHandler),
(r"/login", LoginHandler),
], cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__")
application.listen(5000)
tornado.ioloop.IOLoop.current().start()
在我的代码中我有三个类BaseHandler
, MainHandler
and LoginHandler
。任何帮助将不胜感激。
不要在 Tornado 方法中调用“sleep”:
http://www.tornadoweb.org/en/stable/faq.html
如果您想暂停该方法一段时间以向自己证明它是非阻塞的,请添加from tornado import gen
并尝试:
async def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
yield gen.sleep(10)
self.redirect("/")
或者在 Python 2 中:
@gen.coroutine
def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
yield gen.sleep(10)
self.redirect("/")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)