Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support CORS #223

Closed
reubano opened this issue Jun 20, 2013 · 12 comments

Comments

@reubano
Copy link
Contributor

@reubano reubano commented Jun 20, 2013

There should be an option to enable CORS for cross origin requests.

response.headers['Access-Control-Allow-Origin'] = '*'

@reubano

This comment has been minimized.

Copy link
Contributor Author

@reubano reubano commented Jun 21, 2013

views.py

HEADERS = {'Content-Type': 'application/json; charset=utf-8',
                       'Access-Control-Allow-Origin': '*'}
....
def _search(self):
    ...
    headers = dict(Link=linkstring)
    headers.update(HEADERS)
@klinkin

This comment has been minimized.

Copy link
Contributor

@klinkin klinkin commented Jun 21, 2013

I think that the setting CORS headers is out of scope flask-restless.

simple example:

def add_cors_header(response):
    response.headers['Access-Control-Allow-Origin'] = 'http://partner.xcvbbn.ru'
    response.headers['Access-Control-Allow-Methods'] = 'HEAD, GET, POST, PATCH, PUT, OPTIONS, DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
    response.headers['Access-Control-Allow-Credentials'] = 'true'

    return response

...
bp = api_manager.create_api_blueprint(**options)
bp.after_request(add_cors_header)
@reubano

This comment has been minimized.

Copy link
Contributor Author

@reubano reubano commented Jun 21, 2013

Wow thanks. This helped a ton and should really be in the docs. I would have never figured it out otherwise. This fixes #224 as well!

import config
from savalidation import ValidationError
from flask import Flask

from sqlalchemy.exc import IntegrityError, OperationalError
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager

API_EXCEPTIONS = [
    ValidationError, ValueError, AttributeError, TypeError, IntegrityError,
    OperationalError]

db = SQLAlchemy()


def create_app(config_mode=None, config_file=None):
    # Create webapp instance
    app = Flask(__name__)
    db.init_app(app)

    if config_mode:
        app.config.from_object(getattr(config, config_mode))
    elif config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar('APP_SETTINGS', silent=True)

    def add_cors_header(response):
        allow = 'HEAD, OPTIONS'

        for m in app.config['API_METHODS']:
            allow += ', %s' % m

        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = allow
        response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
        response.headers['Access-Control-Allow-Credentials'] = 'true'
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

    # Create the Flask-Restless API manager.
    mgr = APIManager(app, flask_sqlalchemy_db=db)
    kwargs = {
        'methods': app.config['API_METHODS'],
        'validation_exceptions': API_EXCEPTIONS,
        'allow_functions': app.config['API_ALLOW_FUNCTIONS'],
        'allow_patch_many': app.config['API_ALLOW_PATCH_MANY'],
        'max_results_per_page': app.config['API_MAX_RESULTS_PER_PAGE'],
        'url_prefix': app.config['API_URL_PREFIX']}

    mgr.create_api(Forms, **kwargs)
    app.after_request(add_cors_header)
    return app

from app.models import Forms
@reubano reubano closed this Jun 21, 2013
@klinkin

This comment has been minimized.

Copy link
Contributor

@klinkin klinkin commented Jun 21, 2013

Glad I could help you:)

@jfinkels jfinkels reopened this Jul 29, 2013
@jfinkels

This comment has been minimized.

Copy link
Owner

@jfinkels jfinkels commented Jul 29, 2013

If you think this would be valuable as an example in the documentation, I would like to leave this issue open until it is added there.

@hunterowens

This comment has been minimized.

Copy link

@hunterowens hunterowens commented Jul 2, 2014

This solution no longer works.

Error:
TypeError: 'NoneType' object is not callable

@klinkin

This comment has been minimized.

Copy link
Contributor

@klinkin klinkin commented Jul 2, 2014

@hunterowens what's problem?

@hunterowens

This comment has been minimized.

Copy link

@hunterowens hunterowens commented Jul 2, 2014

@klinkin Operator error. Fixes.

@klinkin

This comment has been minimized.

Copy link
Contributor

@klinkin klinkin commented Jul 2, 2014

@hunterowens Can you provide complete stack trace or just a gist illustrating the issue?

@feedingaliencat

This comment has been minimized.

Copy link

@feedingaliencat feedingaliencat commented Aug 12, 2014

@hunterowens, the solution works!
I was looking for this for hours, thank you @reubano and @klinkin, you solved me the day.
This really should be in documentation.

@jfinkels

This comment has been minimized.

Copy link
Owner

@jfinkels jfinkels commented Aug 12, 2014

I will add this to the documentation now. However, I suspect this is the sort of thing you might want to set at the HTTP server level (nginx or Apache httpd, for example).

@jfinkels

This comment has been minimized.

Copy link
Owner

@jfinkels jfinkels commented Aug 12, 2014

Fixed in 21f9caf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants
You can’t perform that action at this time.