如下面的代码所示,我有一个用于注册的GET,它将其工作委托给POST

class RegistrationHandler(tornado.web.RequestHandler):
    def get(self):
        s = """
          <h1>Register</h1>
              <form method="post" action="/register">
                  <div>
                      <label>User</label>
                      <input name="user_name" value="[email protected]"/>
                  </div>
                  <div>
                      <label>password</label>
                      <input name="password" type="password"/>
                  </div>
                  <div>
                      <input type="submit" value="submit"/>
                  </div>
              </form>
        """
        self.write(s)

    @log_exception()
    def post(self):
        user_name = self.request.arguments['user_name']
        password = self.request.arguments['password']
        log.debug('Registering user with credentials %r' % (user_name, password))
        with sa_session() as db_session:
            User.register(user_name, password, db_session)

当我从我的网络浏览器访问该URL时,我会得到一个注册表,提交后我会得到“403:禁止”。
控制台日志:
2012-10-15 11:27:42,482 - __main__ - DEBUG - Starting server on port 8080
2012-10-15 11:27:49,377 - root - INFO - 304 GET /register (127.0.0.1) 0.78ms
2012-10-15 11:27:53,143 - root - WARNING - 403 POST /register (127.0.0.1): '_xsrf' argument missing from POST
2012-10-15 11:27:53,144 - root - WARNING - 403 POST /register (127.0.0.1) 1.05ms

这个错误是什么意思?我该如何纠正它?谢谢。

最佳答案

我想您的设置中启用了跨站点请求伪造cookie
(默认打开)。
Tornado's XSRF is here
要修复此问题,请在设置中关闭:

settings = {
    "xsrf_cookies": False,
}

注意:通常情况下,您不想关闭此功能,通常会在这样的模板中生成HTML:请注意添加XSRF cookie的XSRF位。
 <form method="post" action="/register">
     <input name="user_name" value="[email protected]"/>
     <input name="password" type="password"/>
     <input type="submit" value="submit"/>
{% raw xsrf_form_html() %}
 </form>

---编辑以下注释---
而不是:
  def get(self):
        loader = template.Loader("resources")
        page_contents = loader.load('register_page.html').generate()
        self.write(page_contents)

做:
  def get(self):
     self.render("../resources/register_page.html")

或者更好:
  def get(self):
     self.render("register_page.html")

(并将其放在模板目录中)

10-03 00:12