我最近尝试遵循龙卷风 cookie 和安全 cookie 概述并给出示例。
当我的服务器尝试执行 set_secure_cookie(..) 时出现一个奇怪的错误:
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/escape.py", line 168, in utf8
assert isinstance(value, unicode)
AssertionError
我做错了什么?
我的龙卷风服务器:
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import Settings
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class MainHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
name = tornado.escape.xhtml_escape(self.current_user)
self.write("Hello, " + name)
class LoginHandler(BaseHandler):
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 Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/login", LoginHandler),
]
settings = {
"template_path":Settings.TEMPLATE_PATH,
"static_path":Settings.STATIC_PATH,
"debug":Settings.DEBUG,
"cookie_secret": Settings.COOKIE_SECRET,
"login_url": "/login"
}
tornado.web.Application.__init__(self, handlers, **settings)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
完整追溯:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 1042, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "/home/gvincent/Dropbox/workspace/scubabook/WebServer.py", line 31, in post
self.set_secure_cookie("user", self.get_argument("name"))
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 426, in set_secure_cookie
self.set_cookie(name, self.create_signed_value(name, value),
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 438, in create_signed_value
name, value)
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 2029, in create_signed_value
signature = _create_signature(secret, name, value, timestamp)
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 2066, in _create_signature
hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/escape.py", line 168, in utf8
assert isinstance(value, unicode)
AssertionError