flask-CORS的尝试和解决

  因为要使用到跨域访问,就尝试了网上常见的一些解决办法,最后经过尝试发现flask有模块可以直接解决这个问题

1.安装flask-cors
pip install -U flask-ocrs
2.在配置文件app/__init__.py设置 
from flask_cors import CORS
def create_app(config_name):
app = Flask(__name__)
CORS(app) 

另外也有尝试过两种办法,但均未达到理想的效果

(1)首选方法是写了一个装饰器,然后在每个请求路由前家=加上去@allow_cross_domain ,也算是一种很麻烦的办法,但更致命的是,PUT方法时候,

  出现了错误:
XMLHttpRequest cannot load http://127.0.0.1:5000/account/status/. Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'http://localhost:5001' is therefore 
not allowed access.
这时候请求变成了option, 看网上原因是CORS的规范定义,,浏览器会做一次 preflight 请求,这次请求询问服务器支持哪些方法所以,这个装饰器的办法就阵亡了
# def allow_cross_domain(fun):
#     @wraps(fun)
#     def wrapper_fun(*args, **kwargs):
#         rst = make_response(fun(*args, **kwargs))
#         
#         rst.headers['Access-Control-Allow-Origin'] = '*'
#         rst.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE'
#         allow_headers = "Referer,Accept,Origin,User-Agent"
#         rst.headers['Access-Control-Allow-Headers'] = allow_headers
#         return rst
#     return wrapper_fun

(2)然后尝试了自定义响应类,重写了Response class,但在测试的过程中,报错super()需要至少一个参数但是没有接受到入参

from flask import Flask, Response
from werkzeug.datastructures import Headers

class MyResponse(Response):
    def __init__(self, response=None, **kwargs):
        kwargs['headers'] = ''
        headers = kwargs.get('headers')
        # 跨域控制 
        origin = ('Access-Control-Allow-Origin', '*')
        methods = ('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, DELETE, PUT')
        if headers:
            headers.add(*origin)
            headers.add(*methods)
        else:
            headers = Headers([origin, methods])
        kwargs['headers'] = headers
        return super().__init__(response, **kwargs)
def create_app(): app = Flask(__name__) app.response_class = MyResponse

你可能感兴趣的:(python)