Momoko,Jinja2和Tornado

时间:2014-10-05 22:55:27

标签: postgresql tornado jinja2 momoko

我的代码存在根本性的问题。这些是我的 龙卷风处理程序与基本身份验证和jinja2作为模板 发动机。以下工作没有momoko数据库部分。

class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db   
    def get_current_user(self):
        return self.get_secure_cookie("user")

class TemplateHandler(BaseHandler):
    """Request handler for writing HTML templates."""
    def render(self, template_name, **kwargs):
        """Renders a Jinja2 template."""
        kwargs['options'] = options.as_dict()
        template = templates.environment.get_template(template_name)
        html = template.render(kwargs)
        self.write(html)

class AuthLoginHandler(TemplateHandler):
    def get(self):
        try:
            errormessage = self.get_argument("error")
        except:
            errormessage = ""
        self.render("login.html", errormessage = errormessage)

    def check_permission(self, password, username):
        if username == "admin" and password == "admin":
            return True
        return False

    def post(self):
        username = self.get_argument("username", "")
        password = self.get_argument("password", "")
        auth = self.check_permission(password, username)
        if auth:
            self.set_current_user(username)
            self.redirect(self.get_argument("next", u"/"))
        else:
            error_msg = u"?error=" + tornado.escape.url_escape("Login incorrect")
            self.redirect(u"/auth/login/" + error_msg)

    def set_current_user(self, user):
        if user:
            self.set_secure_cookie("user", tornado.escape.json_encode(user))
        else:
            self.clear_cookie("user")

class AuthLogoutHandler(TemplateHandler):
    def get(self):
       self.clear_cookie("user")
       self.redirect(self.get_argument("next", "/"))


class MainHandler(TemplateHandler):
    @gen.engine
    def get(self):
        username = tornado.escape.xhtml_escape(self.current_user)
        try:
            cursor = yield momoko.Op(self.db.execute, 'SELECT * FROM products;')
        except Exception as error:
            self.write(str(error))
        res = 'Query results: '+''.join(str(cursor.fetchall()))
        self.render("index.html", username = username, cip = self.request.remote_ip, res = res)

对于登录的客户端,此代码应执行基本查询,然后将结果打印到jinja模板中的已定义位置({{res}})。当我尝试启动服务器时,我得到了这个:

第22行,渲染         kwargs ['options'] = options.as_dict()     AttributeError:'module'对象没有属性'as_dict'

1 个答案:

答案 0 :(得分:0)

我们需要看到你的" import"声明知道什么是错误的。我怀疑你有:

from tornado import options

但你需要:

from tornado.options import options