tornado跨域解决方法

代码

class BaseHandler(tornado.web.RequestHandler):
    #  允许跨域访问的地址
    def allowMyOrigin(self):
        allow_list = [
            'http://127.0.0.1:7100',
        ]
        if 'Origin' in self.request.headers:
            Origin = self.request.headers['Origin']
            # 域名
            re_ret = re.match(r".{1,}\.(xixi.com|haha.com)", Origin)
            # 内网和本地
            re_ret2 = re.match(r"^(192.168.1.*|127.0.0.1.*|192.168.2.*)", Origin)
            if re_ret or re_ret2 or Origin in allow_list:
                self.set_header("Access-Control-Allow-Origin", Origin)  # 这个地方可以写域名也可以是*
                self.set_header("Access-Control-Allow-Headers", "x-requested-with")
                self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

 

调用:

class InterFaceHandler(BaseHandler):
    def set_default_headers(self):
        self.allowMyOrigin()
    def get(self, *args, **kwargs):
        pass

  

 

xsrf_:报错

[W 201029 14:14:43 web:1618] 403 POST /authCenter/admin/siteOwnerEdit (127.0.0.1): '_xsrf' argument missing from POST
[W 201029 14:14:43 web:2106] 403 POST /authCenter/admin/siteOwnerEdit (127.0.0.1) 5.22ms
[I 201029 14:17:40 process:128] Starting 64 processes

 

1:
#把True改为False
app = tornado.web.Application(
    [(r"/", IndexHandler),],
    cookie_secret = "2hcicVu+TqShDpfsjMWQLZ0Mkq5NPEWSk9fi0zsSt3A=",
    xsrf_cookies = True
)



2:
class siteOwnerEdit(BaseHandler):
    def check_xsrf_cookie(self):
        # 非常有用的在单页面禁用xsrf_cookie的检查
        return True

3:
#非模板应用
#下面两种方式都可以起到设置_xsrf Cookie的作用。
class XSRFTokenHandler(RequestHandler):
    """专门用来设置_xsrf Cookie的接口"""
    def get(self):
        **self.xsrf_token**
        self.write("Ok")

class StaticFileHandler(tornado.web.StaticFileHandler):
    """重写StaticFileHandler,构造时触发设置_xsrf Cookie"""
    def __init__(self, *args, **kwargs):
        super(StaticFileHandler, self).__init__(*args, **kwargs)
      	self.xsrf_token

  

 

posted @ 2019-08-27 10:07  zhang_kk  阅读(4369)  评论(0编辑  收藏  举报