3

I'm developing a RESTful application with ExtJS (client) and Flask (server): client and server are linked by a protocol.

The problem comes when I try to do an AJAX request to the server, like this:

Ext.Ajax.request ({
    url: 'http://localhost:5000/user/update/' + userId ,
    method: 'POST' ,
    xmlData: xmlUser ,
    disableCaching: false ,
    headers: {
        'Content-Type': 'application/xml'
    } ,
    success: function (res) {
        // something here
    } ,
    failure: function (res) {
        // something here
    }
});

With the above request, the client is trying to update the user information. Unfortunately, this is a cross-domain request (details).

The server handles that request as follows:

@app.route ("/user/update/<user_id>", methods=['GET', 'POST'])
def user_update (user_id):
  return user_id

What I see on the browser console is an OPTIONS request instead of POST. Then, I tried to start the Flask application on the 80 port but it's not possible, obviously:

app.run (host="127.0.0.1", port=80)

In conclusion, I don't understand how the client can interact with the server if it cannot do any AJAX request.

How can I get around this problem?

Community
  • 1
  • 1
Wilk
  • 7,873
  • 9
  • 46
  • 70

3 Answers3

4

Here's an excellent decorator for CORS with Flask.

http://flask.pocoo.org/snippets/56/

Here's the code for posterity if the link goes dead:

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


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
nathancahill
  • 10,452
  • 9
  • 51
  • 91
1

You get around the problem by using CORS

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
  • Is this the only way to do it? – Wilk Oct 09 '12 at 07:08
  • you could also proxy all requests to external domains thru your domain or, you could use JSONP, but that is read-only. – Neil McGuigan Oct 09 '12 at 15:06
  • Actually, I don't have any external domains: it's just a request-responde from the client to the server, all in localhost. I don't understand why Flask can't run on the Internet port (80) as PHP does. In fact, with PHP I can easily do AJAX requests with no cross-domain issues. This is why I made this thread. – Wilk Oct 09 '12 at 15:23
  • Flask certainly can run on port 80. You can use ```app.run(port=80)```, or more efficiently, use Gunicorn and Nginx to route your requests to Flask. – nathancahill Oct 09 '12 at 16:44
  • by external domain I really mean "any subdomain.domain:port combo" different than what extjs is running on. getting flask to run on 80 is probably your best bet. – Neil McGuigan Oct 09 '12 at 16:58
  • Well, I tried it but two things: first I need to start Flask as root and I don't like it; second the system tells me that the address is already in use. So, I can't start it on port 80. – Wilk Oct 09 '12 at 17:10
0

The module Flask-CORS makes it extremely simple to perform cross-domain requests:

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

See also: https://pypi.python.org/pypi/Flask-Cors

Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49