Skip to content

Instantly share code, notes, and snippets.

@froi
Last active June 30, 2020 05:12
Show Gist options
  • Save froi/fa4b4d3d4f5c5d597dbf to your computer and use it in GitHub Desktop.
Save froi/fa4b4d3d4f5c5d597dbf to your computer and use it in GitHub Desktop.
Simple Python Flask app to demonstrate the use of CORS with Flask-restful

What is CORS (Cross-origin Resource Sharing)

CORS is the way to share resources between different domains. while avoiding potential cross site scripting attacks. If you do not understand what CORS is or just want to learn more on it, I suggest you read one of the following or all if you're awesome:

An understanding of this will definitely help you in future projets.

How to run the files

  1. Make virtualenv environment

    • With virtualenv-wrapper

       $> mkdir cors-test && cd cors-test
       $> mkvirtualenv cors-test
      
    • With virtualenv

       $> mkdir cors-test && cd cors-test
       $> virtualenv env && source env/bin/activate
      
  2. Install requirements

    $> pip install -r requirements.txt
    
  3. To execute the Flask app just run

    $> python app.py
    

    This will use Flask's default port 5000

  4. You can use Python's development server to serve your html

    $> python-m SimpleHTTPServer 8000
    

    The port doesn't need to be 8000 just a high value port that isn't in use.

  5. Open your browser to http://localhost:5000/. You should get {'hello': 'world'} in your browser's JS console.

  6. Now that that's working open http://localhost:8000/give_me_data in your browser. Enter any value in the input text field and click the button below it. You should see {'name': <your_input_val>} in the browser's JS console and the terminal where the Flask app is running.

from flask import Flask
from flask_cors import CORS
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resorces={r'/give_me_data': {"origins": '*'}})
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('name', type=str)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
class GiveMeData(Resource):
def post(self):
args = parser.parse_args()
print args
result = {'name': args['name']}
return result, 200
api.add_resource(HelloWorld, '/')
api.add_resource(GiveMeData, '/give_me_data')
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" async defer>
$('document').ready(function() {
var button = $('#test-btn'),
results = $('#results');
button.click(function(){
$.ajax({
url: 'http://localhost:5000/give_me_data',
type: 'POST',
crossDomain: true,
// contentType: 'application/json',
data: {name:$('#test-input').val()},
success: function(data) {
console.log('success')
console.log(data);
},
fail: function(data) {
console.log('fail')
console.log(data);
},
error: function(data) {
console.log('error')
console.log(data)
}
});
});
});
</script>
</head>
<body>
<div id='container'>
<input type="text" id="test-input" name="test-inpout" placeholder=""> <br />
<button id="test-btn">Click</button>
</div>
<div id="results"></div>
</body>
</html>
aniso8601==0.92
Flask==0.10.1
Flask-Cors==1.10.2
Flask-RESTful==0.3.1
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
pytz==2014.10
six==1.9.0
Werkzeug==0.10.1
@Atarity
Copy link

Atarity commented Feb 13, 2020

This simple example saves me tons of time. The only notice: since Flask-Cors and Flask-RESTful updated it should be imported like:

from flask_cors import CORS
from flask_restful import Resource, Api, reqparse

@froi
Copy link
Author

froi commented Jun 30, 2020

@Atarity I'm glad this helps!

I've updated the Python code. Thanks for the suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment