异步登录龙卷风 [英] Asynchronous login tornado
问题描述
我使用Tornado创建了一个适用于同步方法的登录页面.现在我想使其异步.那么我应该对以下代码进行哪些更改:
I used Tornado to create a login page which works on synchronous method.Now I want to make it asynchronous. So what are the changes I should do to the following code:
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
和 LoginHandler
.任何帮助将不胜感激.
In my code I have three classes BaseHandler
, MainHandler
and LoginHandler
. Any help will be appreciated.
推荐答案
不要在Tornado方法中调用"sleep":
Don't call "sleep" in a Tornado method:
http://www.tornadoweb.org/en/stable/faq.html
如果您想暂停该方法一段时间以向自己证明它是非阻塞的,请从tornado import gen中添加并尝试:
If you want to pause the method for a while to prove to yourself that it's non-blocking, add from tornado import gen
and try:
async def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
yield gen.sleep(10)
self.redirect("/")
或者在Python 2中:
Or in Python 2:
@gen.coroutine
def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
yield gen.sleep(10)
self.redirect("/")
这篇关于异步登录龙卷风的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!