本文介绍了Tornado 重定向导致 TypeError: initialize() 缺少 1 个必需的位置参数:'url'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Tornado 和 Web 服务开发的新手,目前正在实现一个用于练习 Tornado 模块的微型 Web.
这是我用于服务器的python代码
import bcrypt导入并发.futures#导入 MySQL 数据库#导入降价导入 os.path进口重新导入子流程#导入torndb导入 tornado.escape从龙卷风进口发电机导入 tornado.httpserver导入 tornado.ioloop导入 tornado.options导入 tornado.web导入 unicodedata从 tornado.options 导入定义,选项定义(端口",默认值=8889,help='在给定端口上运行',类型=整数)类 HomeHandler(tornado.web.RequestHandler):定义获取(自我):#这里登录self.render('index.html')def post(self):def readcodebook(codebook):使用 open(codebook,'r+') 作为 f:CodeLines=f.read().split('\n')组合={}对于 CodeLines 中的 c:如果len(c)>0:组合[c.split('\t')[0]]=c.split('\t')[1]返回组合UserFile='/home/john/PyServer/Users/codebook.txt'CodeBook=readcodebook(UserFile)如果 CodeBook.keys() 中的 self.get_argument("login"):如果 CodeBook[self.get_argument("login")]==self.get_argument("password"):#正确的密码self.redirect(self.get_argument("next","/display/"))别的:#密码不正确self.render("index.html", error='密码错误!')返回别的:#找不到用户self.render("index.html", error="找不到账户!")返回类 DisplayHandler(tornado.web.RedirectHandler):定义获取(自我):self.render("displaycontent.html")经过类应用程序(tornado.web.Application):def __init__(self):处理程序 = [(r"/", HomeHandler),(r"/display/", DisplayHandler),]设置 = 字典(#blog_title=u"龙卷风博客",template_path=os.path.join(os.path.dirname(__file__), "templates"),static_path=os.path.join(os.path.dirname(__file__), "static"),#ui_modules={"Entry": EntryModule},#xsrf_cookies=真,#cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",#login_url="/auth/login",调试=真,)tornado.web.Application.__init__(self,handlers,**settings)如果 __name__=="__main__":tornado.options.parse_command_line()http_server=tornado.httpserver.HTTPServer(Application())http_server.listen(options.port)tornado.ioloop.IOLoop.instance().start()
这是用户登录的 index.html:
CSSFlow登录表格以前的下一个推特FacebookRSS通讯<!DOCTYPE html><!--[如果是 IE 7]><html class="lt-ie9 lt-ie8 lt-ie7" lang="en"><![endif]--><!--[如果 IE 7]><html class="lt-ie9 lt-ie8" lang="en"><![endif]--><!--[如果 IE 8]><html class="lt-ie9" lang="en"><![endif]--><!--[if gt IE 8]><!--><html lang="zh-cn"><!--<![endif]--><头><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>登录表单</title><link rel="stylesheet" href="css/style.css"><!--[如果是 IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->头部><身体><section class="容器"><div class="登录"><h1>登录到 Web 应用程序</h1><form method="post" action="/"><p><input type="text" name="login" value="" placeholder="用户名或电子邮件"></p><p><input type="password" name="password" value="" placeholder="密码"></p><p class="remember_me"><标签><input type="checkbox" name="remember_me" id="remember_me">在这台电脑上记住我标签></p><p class="submit"><input type="submit" name="commit" value="Login"></p></表单>
<div class="登录帮助"><p>忘记密码?<a href="index.html">点击此处重置</a>.</p>
</节><section class="关于"><p class="关于链接"><a href="http://www.cssflow.com/snippets/login-form" target="_parent">查看文章</a><a href="http://www.cssflow.com/snippets/login-form.zip" target="_parent">下载</a></p><p class="关于作者">&复制;2012–2013 <a href="http://thibaut.me" target="_blank">Thibaut Corouble</a>——<a href="http://www.cssflow.com/mit-license" target="_blank">MIT 许可证</a><br></html>现场演示HTML 源代码SCSS 源鸣叫分享查看文章下载全部下载90% 无限下载从超过 300,000 种矢量、图形和图形中选择照片广告通过碳现在的问题是,当我使用正确的用户名和密码点击 index.html 中的提交按钮时,tornado 会抛出一个未捕获的异常,并在下面显示错误 404 未在 Web 浏览器中找到:
[E 170108 11:21:55 http1connection:54] 未捕获的异常回溯(最近一次调用最后一次):文件/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/http1connection.py",第238行,_read_message委托.完成()文件/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/httpserver.py",第289行,完成self.delegate.finish()文件/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py",第2022行,完成自我执行()文件/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py",第2042行,在执行中**self.handler_kwargs)文件/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py",第183行,在__init__self.initialize(**kwargs)类型错误:initialize() 缺少 1 个必需的位置参数:'url'
这里有人能指出解决这个问题的方法吗?非常感谢!
解决方案
Tornado 为您提供了两种完成重定向的方法.一种使用 RedirectHandler 和另一种使用redirect RequestHandler 的方法.
>
在你上面的例子中,你混合了这两种方式,导致了你得到的错误.
在您的示例中,由于您使用第二种方式(RequestHandler.redirect),要在成功登录时完成重定向到 displaycontent.html
,您需要替换 displaycontent.html
的父类code>DisplayHandler 成为RequestHandler
而不是 RedirectHandler
.
例如
class DisplayHandler(tornado.web.RequestHandler):定义获取(自我):self.render("displaycontent.html")
此外,redirect 方法的参数只能是您要重定向到的 url(或别名).
例如
#正确密码self.redirect("/display/")
如果您对重定向的更多阅读感兴趣,请遵循此链接.
I am new to tornado and web service development, and currently implementing a tiny web for practising tornado module.
This is the python code I used for my server
import bcrypt
import concurrent.futures
#import MySQLdb
#import markdown
import os.path
import re
import subprocess
#import torndb
import tornado.escape
from tornado import gen
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import unicodedata
from tornado.options import define, options
define("port",default=8889,help='run on the given port',type=int)
class HomeHandler(tornado.web.RequestHandler):
def get(self):
#login here
self.render('index.html')
def post(self):
def readcodebook(codebook):
with open(codebook,'r+') as f:
CodeLines=f.read().split('\n')
combinations={}
for c in CodeLines:
if len(c)>0:
combinations[c.split('\t')[0]]=c.split('\t')[1]
return combinations
UserFile='/home/john/PyServer/Users/codebook.txt'
CodeBook=readcodebook(UserFile)
if self.get_argument("login") in CodeBook.keys():
if CodeBook[self.get_argument("login")]==self.get_argument("password"):
#correct pwd
self.redirect(self.get_argument("next","/display/"))
else:
#incorrect pwd
self.render("index.html", error='incorrect password!')
return
else:
#user not found
self.render("index.html", error="account not found!")
return
class DisplayHandler(tornado.web.RedirectHandler):
def get(self):
self.render("displaycontent.html")
pass
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", HomeHandler),
(r"/display/", DisplayHandler),
]
settings = dict(
#blog_title=u"Tornado Blog",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
#ui_modules={"Entry": EntryModule},
#xsrf_cookies=True,
#cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
#login_url="/auth/login",
debug=True,
)
tornado.web.Application.__init__(self,handlers,**settings)
if __name__=="__main__":
tornado.options.parse_command_line()
http_server=tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
and this is the index.html for user logon:
CSSFlow
Login Form
Previous
Next
Twitter
Facebook
RSS
Newsletter
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body>
<section class="container">
<div class="login">
<h1>Login to Web App</h1>
<form method="post" action="/">
<p><input type="text" name="login" value="" placeholder="Username or Email"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
<div class="login-help">
<p>Forgot your password? <a href="index.html">Click here to reset it</a>.</p>
</div>
</section>
<section class="about">
<p class="about-links">
<a href="http://www.cssflow.com/snippets/login-form" target="_parent">View Article</a>
<a href="http://www.cssflow.com/snippets/login-form.zip" target="_parent">Download</a>
</p>
<p class="about-author">
© 2012–2013 <a href="http://thibaut.me" target="_blank">Thibaut Courouble</a> -
<a href="http://www.cssflow.com/mit-license" target="_blank">MIT License</a><br>
Original PSD by <a href="http://www.premiumpixels.com/freebies/clean-simple-login-form-psd/" target="_blank">Orman Clark</a>
</section>
</body>
</html>
Live Demo
HTML Source
SCSS Source
Tweet
Share
View Article
Download
Download All
90% Unlimited Downloads Choose from Over 300,000 Vectors, Graphics & Photos.ads via Carbon
The problem now is that tornado will throw an uncaught exception with description below and shows Error 404 not found in web browser, when I click submit button in index.html with correct username and password:
[E 170108 11:21:55 http1connection:54] Uncaught exception
Traceback (most recent call last):
File "/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/httpserver.py", line 289, in finish
self.delegate.finish()
File "/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py", line 2022, in finish
self.execute()
File "/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py", line 2042, in execute
**self.handler_kwargs)
File "/home/gaobo/anaconda3/lib/python3.5/site-packages/tornado/web.py", line 183, in __init__
self.initialize(**kwargs)
TypeError: initialize() missing 1 required positional argument: 'url'
Could anybody here point out a way to fix this problem? Thanks a lot!
解决方案
Tornado offers you two ways to accomplish a redirection. One using the RedirectHandler and the other way using the redirect method of the RequestHandler.
On your example above you mixed these two ways causing the error you get.
On your example, since you use the second way (RequestHandler.redirect), to accomplish a redirection to the displaycontent.html
on a successful login, you need to replace the parent class of the DisplayHandler
to be theRequestHandler
innstead of the RedirectHandler
.
eg.
class DisplayHandler(tornado.web.RequestHandler):
def get(self):
self.render("displaycontent.html")
Also the parameters of the redirect method should only be the url(or alias) you want to redirect to.
eg.
#correct pwd
self.redirect("/display/")
If you are interested in some more reading for the redirection follow this link.
这篇关于Tornado 重定向导致 TypeError: initialize() 缺少 1 个必需的位置参数:'url'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!