由于某种原因,我无法在MainHandler之外实例化set_cookie .. 这是一个小代码,以显示我想要做什么.. 任何人都可以帮忙吗?
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from GenCookie import *
class MainHandler(tornado.web.RequestHandler):
def get(self):
g=GenCookie()
response = g.genCookie()
class GenCookie:
def genCookie(self):
print self.request.remote_ip
print self.cookies
print self.request.headers
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
if ("uid" in cookies):
self.set_cookie("uid", value=cookies["uid"],expires=expires)
else:
self.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
return
有什么想法吗?
答案 0 :(得分:7)
我认为这解释了自己。
set_cookie是tornado.web.RequestHandler
的方法在代码“self.set_cookie”中,self指的是GenCookie类的对象。
您的代码可以修改以传递必要的参考
class MainHandler(tornado.web.RequestHandler):
def get(self):
g=GenCookie(self)
response = g.genCookie()
class GenCookie:
def __init__(self, reqHandler):
self.reqHandler = reqHandler
def genCookie(self):
print self.request.remote_ip
print self.cookies
print self.request.headers
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
if ("uid" in self.cookies):
self.reqHandler.set_cookie("uid", value=self.cookies["uid"],expires=expires)
else:
self.reqHandler.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
return