用Flask解决跨源数据共享问题 [英] Solve Cross Origin Resource Sharing with Flask

查看:310
本文介绍了用Flask解决跨源数据共享问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 ajax Flask 如何使用从ajax发布的数据?):

  $。ajax({
url:http://127.0.0.1:5000/foo,
type:POST ,
contentType:application / json,
data:JSON.stringify({'inputVar':1}),
success:function(data){
alert 成功+数据);
}
});

我得到 跨源资源共享(CORS) 错误:

 否请求的资源上存在Access-Control-Allow-Origin标题。 
原因'null'因此不被允许访问。
响应的HTTP状态码为500.

我尝试用以下两种方法解决,但看起来没有任何作用。
$ b


  1. 使用Flask-CORS

  2. ol>

    这是一个 Flask 扩展,用于处理 CORS 可能是跨网站AJAX。



    我的 pythonServer.py 使用此解决方案:

      from flask import Flask 
    from flask.ext .cors import CORS,cross_origin

    app = Flask(__ name__)
    cors = CORS(app,resources = {r/ foo:{origins:*}})
    app.config ['CORS_HEADERS'] ='Content-Type'

    @ app.route('/ foo',methods = ['POST','OPTIONS'])
    @cross_origin(origin ='*',headers = ['Content-Type','Authorization'])
    def foo():
    return request.json ['inputVar']

    if __name__ =='__main__':
    app.run()




    1. 使用特定的Flask Decorator

    官方 Flask代码片段定义了一个装饰器,它应该允许 CORS 对其进行装饰。





    我的 pythonServer.py 使用这个解决方案:

      from flask import Flask,make_response,request,current_app $ b $ from datetime import timedelta 
    from functools import update_wrapper
    $ b $ app = Flask(__ name__)
    $ b $ def def crossdomain(origin = None,methods = None,headers = None,
    max_age = 21600,attach_to_all =真,
    automatic_options =真):
    如果方法不是无:
    methods =','.join(对方法中的x进行排序(x.upper()))
    如果标题不是None而不是isinstance(headers,basestring):
    headers =','.join(x.upper()for x in header)
    如果不是isinstance(origin,basestring):
    origin =','.join(origin)
    如果isinstance(max_age,timedelta):
    max_age = max_age.total_seconds()
    $ b $ def get_methods():
    如果方法不是None:
    返回方法

    options_resp = current_app.make_default_options_response()
    返回options_resp.headers ['allow']

    def decorator(f):
    def wrapped_function(* args,** kwargs):
    if auto_options and request.method =='OPTIONS':
    resp = current_app.make_default_options_response()
    else:
    resp = make_response(f(* args,** kwargs))
    如果不是attach_to_all和request.method!='OPTIONS':
    return resp

    h = r esp.headers
    $ bh ['Access-Control-Allow-Origin'] = origin $ b $ ['Access-Control-Allow-Methods'] = get_methods()$ b $ ['Access -Control-Max-Age'] = str(max_age)
    如果标题不是无:
    h ['Access-Control-Allow-Headers'] =标题
    return resp

    f.provide_automatic_options = False
    return update_wrapper(wrapped_function,f)
    返回装饰器

    @ app.route('/ foo',methods = ['GET' ,'POST','OPTIONS'])
    @crossdomain(origin =*)
    def foo():
    返回request.json ['inputVar']

    if __name__ =='__main__':
    app.run()

    <你可以给一些为什么是这样的指示吗?



    它像一个冠军,修改了一下你的代码。 nitialization
    app = Flask(__ name__)
    app.config ['SECRET_KEY'] ='快速的棕色狐狸跳过懒狗'
    app.config ['CORS_HEADERS'] ='内容类型'

    cors = CORS(app,resources = {r/ foo:{origins:http:// localhost:port}})

    @ app.route('/ foo',methods = ['POST'])
    @cross_origin(origin ='localhost',headers = ['Content- Type','Authorization'])
    def foo():
    return request.json ['inputVar']

    if __name__ =='__main__':
    app.run()

    我用localhost替换了*。因为正如我在许多博客和文章中读到的,您应该允许访问特定的域名

    For the following ajax post request for Flask (how can I use data posted from ajax in flask?):

    $.ajax({
        url: "http://127.0.0.1:5000/foo", 
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({'inputVar': 1}),
        success: function( data ) { 
            alert( "success" + data );
        }   
    });
    

    I get a Cross Origin Resource Sharing (CORS) error:

    No 'Access-Control-Allow-Origin' header is present on the requested resource. 
    Origin 'null' is therefore not allowed access. 
    The response had HTTP status code 500.
    

    I tried solving it in the two following ways, but none seems to work.

    1. Using Flask-CORS

    This is a Flask extension for handling CORS that should make cross-origin AJAX possible.

    My pythonServer.py using this solution:

    from flask import Flask
    from flask.ext.cors import CORS, cross_origin
    
    app = Flask(__name__)
    cors = CORS(app, resources={r"/foo": {"origins": "*"}})
    app.config['CORS_HEADERS'] = 'Content-Type'
    
    @app.route('/foo', methods=['POST','OPTIONS'])
    @cross_origin(origin='*',headers=['Content-Type','Authorization'])
    def foo():
        return request.json['inputVar']
    
    if __name__ == '__main__':
        app.run()
    

    1. Using specific Flask Decorator

    This is an official Flask code snippet defining a decorator that should allow CORS on the functions it decorates.

    My pythonServer.py using this solution:

    from flask import Flask, make_response, request, current_app
    from datetime import timedelta
    from functools import update_wrapper
    
    app = Flask(__name__)
    
    def crossdomain(origin=None, methods=None, headers=None,
                    max_age=21600, attach_to_all=True,
                    automatic_options=True):
        if methods is not None:
            methods = ', '.join(sorted(x.upper() for x in methods))
        if headers is not None and not isinstance(headers, basestring):
            headers = ', '.join(x.upper() for x in headers)
        if not isinstance(origin, basestring):
            origin = ', '.join(origin)
        if isinstance(max_age, timedelta):
            max_age = max_age.total_seconds()
    
        def get_methods():
            if methods is not None:
                return methods
    
            options_resp = current_app.make_default_options_response()
            return options_resp.headers['allow']
    
        def decorator(f):
            def wrapped_function(*args, **kwargs):
                if automatic_options and request.method == 'OPTIONS':
                    resp = current_app.make_default_options_response()
                else:
                    resp = make_response(f(*args, **kwargs))
                if not attach_to_all and request.method != 'OPTIONS':
                    return resp
    
                h = resp.headers
    
                h['Access-Control-Allow-Origin'] = origin
                h['Access-Control-Allow-Methods'] = get_methods()
                h['Access-Control-Max-Age'] = str(max_age)
                if headers is not None:
                    h['Access-Control-Allow-Headers'] = headers
                return resp
    
            f.provide_automatic_options = False
            return update_wrapper(wrapped_function, f)
        return decorator
    
    @app.route('/foo', methods=['GET','POST','OPTIONS'])
    @crossdomain(origin="*")
    def foo():
        return request.json['inputVar']
    
    if __name__ == '__main__':
        app.run()
    

    Can you please give some some indication of why that is?

    解决方案

    @Matt:

    It worked like a champ, after bit modification to your code

    # initialization
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
    app.config['CORS_HEADERS'] = 'Content-Type'
    
    cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})
    
    @app.route('/foo', methods=['POST'])
    @cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
    def foo():
        return request.json['inputVar']
    
    if __name__ == '__main__':
       app.run()
    

    I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain

    这篇关于用Flask解决跨源数据共享问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆