#!/usr/bin/python # -*- coding: UTF-8 -*- #验证码 import tornado.ioloop import tornado.web class CrsfHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.render("crsf.html") def post(self, *args, **kwargs): self.write("csrf.post") settings = { "xsrf_cookies": True, } class CheckCodeHandler(tornado.web.RequestHandler): def get(self): import io import check_code mstream = io.BytesIO() # 创建图片 写入验证码 img, code = check_code.create_validate_code() # 图片对象写入到mstream img.save(mstream, "GIF") # self.session["CheckCode"] = code print(mstream.getvalue()) self.write(mstream.getvalue()) class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html",) application = tornado.web.Application([ (r"/index", MainHandler), #(r"/check_code", CheckCodeHandler), (r"/crsf", CrsfHandler), ],**settings) if __name__ == "__main__": application.listen(5555) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/crsf" method="post"> {% raw xsrf_form_html() %} <p><input name="name" value=""></p> <p><input name="pwd" value=""></p> <p> <input name="valide" value="" placeholder="验证码"> <input type="submit" value="submit" > </p> </form> <script type="text/javascript"> function ChangeCode() { var code = document.getElementById(‘imgCode‘); code.src += ‘?‘; } </script> </body> </html>
Ajax使用时,本质上就是去获取本地的cookie,携带cookie再来发送请求
function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } jQuery.postJSON = function(url, args, callback) { args._xsrf = getCookie("_xsrf"); $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST", success: function(response) { callback(eval("(" + response + ")")); }}); };
时间: 2024-11-04 09:17:26