我正在尝试向我构建的Web应用程序添加一些用户身份验证,以便即时通讯使用此处龙卷风提供的资源(http://www.tornadoweb.org/en/stable/guide/security.html)
除非我故意不匹配我的登录处理程序并重定向(/ login),否则它将超时,在这种情况下,我会得到404。
我提供了我的代码,因为问题在这里,所以我将一些内容简化为基本内容。但我不确定在哪里。任何帮助都是伟大的
import os
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.options import options, define
# Define available options
define("port", default=8888, type=int, help="run on the given port")
PORT = 8888
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class MainHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
# Send our main document
if not self.current_user:
self.redirect("/login")
return
self.render("index.html")
class LoginHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
self.write('<html><body><form action="/login" method="post">'
'Name: <input type="text" name="name">'
'<input type="submit" value="Sign in">'
'</form></body></html>')
def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
self.redirect("/")
class TornadoWebServer(tornado.web.Application):
' Tornado Webserver Application...'
def __init__(self):
#Url to its handler mapping.
handlers = [(r"/", MainHandler),
(r"/login", LoginHandler),
(r"/images/(.*)", tornado.web.StaticFileHandler, {"path": "web/images"}),
(r"/js/(.*)", tornado.web.StaticFileHandler, {"path": "web/js"}),
(r"/style/(.*)", tornado.web.StaticFileHandler, {"path": "web/style"})]
#Other Basic Settings..
settings = dict(
cookie_secret="set_this_later",
login_url="/login",
template_path=os.path.join(os.path.dirname(__file__), "web"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
debug=True)
#Initialize Base class also.
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == '__main__':
#Tornado Application
print("Initializing Tornado Webapplications settings...")
application = TornadoWebServer()
# Start the HTTP Server
print("Starting Tornado HTTPServer on port %i" % PORT)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(PORT)
# Get a handle to the instance of IOLoop
ioloop = tornado.ioloop.IOLoop.instance()
# Start the IOLoop
ioloop.start()
答案 0 :(得分:2)
您在获取请求时使用@ tornado.web.asynchronous装饰器,删除它可以解决问题,或者如果需要,可以在写入命令后调用self.finish()。
您可以在what does @tornado.web.asynchronous decorator mean?
处找到有关此装饰器的更多信息。这是在登录处理程序上使用self.finish的示例
class LoginHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
self.write('<html><body><form action="/login" method="post">'
'Name: <input type="text" name="name">'
'<input type="submit" value="Sign in">'
'</form></body></html>')
self.finish()
def post(self):
self.set_secure_cookie("user", self.get_argument("name"))
self.redirect("/")