Python Flask Cors 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28461001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:19:10  来源:igfitidea点击:

Python Flask Cors Issue

javascriptjquerypythonajaxflask

提问by Max Baldwin

I am kind of new to Python, but I have had the same issue working with Node apps. I am making a pretty standard jQuery AJAX request to my local Python sever:

我对 Python 有点陌生,但我在使用 Node 应用程序时遇到了同样的问题。我正在向我的本地 Python 服务器发出一个非常标准的 jQuery AJAX 请求:

init: function(callback) {
            var token = _config.get_token();

            $.ajax({
                    url: 'http://localhost:5000/api/ia/v1/user_likes',
                    type: 'POST',
                    contentType: 'application/json',
                    datatype: 'json',
                    data: token
                })
                .done(function(data) {
                    callback(data);
                })
                .fail(function(err) {
                    callback(err);
                });

            callback(token);
        }

I can confirm that the variable token is confirming like this:

我可以确认变量令牌是这样确认的:

Object {access_token: "791415154.2c0a5f7.4d707361de394512a29682f9cb2d2846", campaign_id: "102"}

But I am getting this error from my javascript console:

但是我从我的 javascript 控制台收到这个错误:

XMLHttpRequest cannot load http://localhost:5000/api/ia/v1/user_likes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s3.amazonaws.com' is therefore not allowed access. The response had HTTP status code 500.

I have found that when I am building Node apps that this is a cors error. The page that I am running the jQuery AJAX request from is http. Here are the parts of my Python code that I believe I am configuring incorrectly:

我发现当我构建 Node 应用程序时,这是一个 cors 错误。我正在运行 jQuery AJAX 请求的页面是 http。以下是我认为我配置不正确的 Python 代码部分:

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

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'application/json'

And the route:

和路线:

@app.route("/api/ia/v1/user_likes", methods=['POST', 'OPTIONS'])
def user_likes():
    validate = validate_request(request.data)

    return 'something'

My Python error is also returning an error because the request is never making it to this line of code:

我的 Python 错误也返回了一个错误,因为请求永远不会到达这行代码:

def validate_request(object_from_user):
    load_object = json.loads(object_from_user)

I can fix that later. Anyway, does anyone have any suggestions for Cors configurations for Python?

我可以稍后修复它。无论如何,有人对 Python 的 Cors 配置有什么建议吗?

回答by Derek

use the cors decorator after the route decorator.

在路由装饰器之后使用 cors 装饰器。

here's a snippet from the documentation...

这是文档中的一个片段...

@app.route("/")
@cross_origin() # allow all origins all methods.
def helloWorld():
  return "Hello, cross-origin-world!"

now, it appears you are using json, if that's the case, you should likely just read the documentation as it specifically mentions this use case, and what cors_headers to set... it's below the fold, but this documentation is well written and easy to understand.

现在,您似乎正在使用 json,如果是这种情况,您可能应该阅读文档,因为它特别提到了这个用例,以及要设置的 cors_headers ......了解。

http://flask-cors.readthedocs.org/en/latest/#using-json-with-cors

http://flask-cors.readthedocs.org/en/latest/#using-json-with-cors

回答by Shasti

The below solution worked for me. I included a method that will add the headers necessary for you and then raise the HTTP response. Ex:

以下解决方案对我有用。我包含了一个方法,该方法将添加您所需的标头,然后引发 HTTP 响应。前任:

def some_method(response_data, status_code):
    response_data = //here you can manipulate the data, JSONify, convert arrays into objects or vice versa
    headers = {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": '*',
        "Access-Control-Allow-Methods": 'PUT, GET, POST, DELETE, OPTIONS',
        "Access-Control-Allow-Headers": 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
        }
    //THEN RAISE HTTPResponse
    raise HTTPResponse(status, headers, body)

Note: The above method is not python compiling so you may have to edit it.

注意:上面的方法不是python编译的,所以你可能需要编辑它。

回答by lyfing

Here is how to get your hand dirty by handling the CORS detail all by yourself:

以下是如何通过自己处理 CORS 细节来弄脏你的手:

handle_result = {'result': True, 'msg': 'success'}

try:
    # origin, where does this request come from, like www.amazon.com
    origin = flask.request.environ['HTTP_ORIGIN']
except KeyError:
    origin = None

# only accept CORS request from amazon.com
if origin and origin.find('.amazon.com') > -1:
    resp = flask.make_response(str(handle_result))
    resp.headers['Content-Type'] = 'application/json'

    h = resp.headers
    # prepare headers for CORS authentication
    h['Access-Control-Allow-Origin'] = origin
    h['Access-Control-Allow-Methods'] = 'GET'
    h['Access-Control-Allow-Headers'] = 'X-Requested-With'

    resp.headers = h
    return resp

return flask.abort(403)

回答by GyuHyeon Choi

Try this:

尝试这个:

@app.after_request
def add_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')

I've tried @cross_origin tutorial on the Flask website,however, it did not work for me.

我已经在 Flask 网站上尝试过 @cross_origin 教程,但是,它对我不起作用。

But it seems like you can add headers to your response later.

但似乎您可以稍后在响应中添加标头。

Here is my remaining code that I think it may be useful.

这是我认为可能有用的剩余代码。

from flask import Flask, request
from sklearn.externals import joblib

app = Flask(__name__)

回答by user7176771

Flask has the flask-corsmodule. Following is the code snippet as well as the procedure.

Flask 有flask-cors模块。以下是代码片段以及过程。

  1. pip install -U flask-cors

  2. Add this lines in your flask application:

    from flask import Flask
    from flask_cors import CORS, cross_origin
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route("/")
    def helloWorld():
        return "Hello world"
    
  1. pip install -U flask-cors

  2. 在您的烧瓶应用程序中添加以下行:

    from flask import Flask
    from flask_cors import CORS, cross_origin
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route("/")
    def helloWorld():
        return "Hello world"
    

See more by clicking on this link

点击此链接查看更多

回答by Alan Dong

After I tried others suggestions and answers. Here's what I use, which works.

在我尝试了其他人的建议和答案之后。这是我使用的,它有效。

Steps:

脚步:

  1. pip install flask flask-cors

  2. Copy and paste this in app.pyfile

  1. pip install flask flask-cors

  2. 复制并粘贴到app.py文件中

Code

代码

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, support_credentials=True)

@app.route("/login")
@cross_origin(supports_credentials=True)
def login():
  return jsonify({'success': 'ok'})

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000, debug=True)
  1. python app.py
  1. python app.py

Note: be sure in your client's ajax configuration has the following:

注意:请确保在您客户端的 ajax 配置中具有以下内容:

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true,
    contentType: 'application/json; charset=utf-8'
});

If one wonders, support_credentials=Truejust means it sends cookies along the payload back and forth.

如果有人想知道,support_credentials=True这只是意味着它沿着有效载荷来回发送 cookie。

回答by Manivannan Murugavel

Please use @cross_origin(origin='*') in your python file

请在你的python文件中使用@cross_origin(origin='*')

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)

@app.route("/login", methods = ['GET'])
@cross_origin(origin='*')
def login():
  return jsonify({'success': 'ok'})

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000, debug=True)

回答by Dorian

Based on GyuHyeon Choi's response, but with added return responseand an extra Access-Control-Expose-Headersworked for me.

基于 GyuHyeon Choi 的回应,但添加return response和额外的内容Access-Control-Expose-Headers对我有用。

@app.after_request
def add_headers(response):
    response.headers.add('Content-Type', 'application/json')
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Expose-Headers', 'Content-Type,Content-Length,Authorization,X-Pagination')
    return response

回答by Dila Gurung

On client side you only need to ensure that kind of data your server is dealing with. For example form data or json.

在客户端,您只需要确保您的服务器正在处理的数据类型。例如表单数据或 json。

Note: The placement of cross_origin should be right.

注意:cross_origin 的位置应该是对的。

For me the code written below did magic

对我来说,下面写的代码很神奇

from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app=Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/api/test', methods=['POST', 'GET','OPTIONS'])
@cross_origin(supports_credentials=True)
def index():
    if(request.method=='POST'):
     some_json=request.get_json()
     return jsonify({"key":some_json})
    else:
        return jsonify({"GET":"GET"})


if __name__=="__main__":
    app.run(host='0.0.0.0', port=5000)

回答by naik899

I have installed flask using the following command and using the declaration like this:

我已经使用以下命令安装了 Flask,并使用了这样的声明:

pips3.6 install --user flask-cors

pips3.6 install --user flask-cors

  from flask_cors import CORS   
    app = Flask(__name__)
    CORS(app)