Python Crown Problem

I'm kind of new to Python, but I had the same problem as with Node applications. I am making a pretty standard jQuery AJAX request for my local Python:

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 confirmed as follows:

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

But I get this error from my javascript console:

 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 found that when I create a Node application, this is a cors error. The page where I run the JQuery AJAX request is http. Here is the part of my Python code that I believe is incorrectly configured:

 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' 

The My Python error also returns an error, because the request never falls into this line of code:

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

I can fix it later. Anyway, does anyone have any suggestions for setting up Cors for Python?

+14
source share
10 answers

After I tried other suggestions and answers. Here is what I use, what works.

Steps:

  • pip install flask flask-cors

  • Copy and paste this into the app.py file

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

Note: make sure the ajax client configuration has the following:

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

If someone wonders, support_credentials=True simply means that he sends cookies on the payload back and forth.

+13
source

The flask has a bulb-cors module. Below is a code snippet and procedure.

  1. pip install -U flask-cors

  2. Add these lines to your jar application:

     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.

+7
source

Here's how to get your hand dirty by completely processing the CORS part:

 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) 
+4
source

use the cors decorator after the route decorator.

here is a snippet from the documentation ...

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

now it looks like you are using json, if so, you are likely to just read the documentation, as it specifically mentions this use case, and what cors_headers specify ... it is below the fold, but this documentation is well written and understandable.

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

+3
source

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

 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) 
+2
source

The solution below worked for me. I have included a method that will add the headers you need and then will raise an HTTP response. Example:

 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 compilation, so you may have to edit it.

0
source

Try the following:

 @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 tried the @cross_origin tutorial on the Flask website, however it didn't work for me.

But it looks like you can add headers to your answer later.

Here is my remaining code, which I think might be useful.

 from flask import Flask, request from sklearn.externals import joblib app = Flask(__name__) 
0
source

we need to import CORS into a .py file from flask_cors; import CORS, cross_origin CORS (app, support_credentials = True)

0
source

Based on GyuHyeon Choi's answer, but with added return response and optional Access-Control-Expose-Headers worked for me.

 @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 
0
source

On the client side, you only need to make sure that your server data is dealing. For example, form data or JSON.

Note: cross_origin placement must be correct.

For me, the code below did the 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) 
0
source

Source: https://habr.com/ru/post/982336/


All Articles