Git Product home page Git Product logo

flask-cors's Introduction

Flask-CORS

Build Status Latest Version Supported Python versions License

A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.

This package has a simple philosophy: when you want to enable CORS, you wish to enable it for all use cases on a domain. This means no mucking around with different allowed headers, methods, etc.

By default, submission of cookies across domains is disabled due to the security implications. Please see the documentation for how to enable credential'ed requests, and please make sure you add some sort of CSRF protection before doing so!

Installation

Install the extension with using pip, or easy_install.

$ pip install -U flask-cors

Usage

This package exposes a Flask extension which by default enables CORS support on all routes, for all origins and methods. It allows parameterization of all CORS headers on a per-resource level. The package also contains a decorator, for those who prefer this approach.

Simple Usage

In the simplest case, initialize the Flask-Cors extension with default arguments in order to allow CORS for all domains on all routes. See the full list of options in the documentation.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

Resource specific CORS

Alternatively, you can specify CORS options on a resource and origin level of granularity by passing a dictionary as the resources option, mapping paths to a set of options. See the full list of options in the documentation.

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

@app.route("/api/v1/users")
def list_users():
  return "user example"

Route specific CORS via decorator

This extension also exposes a simple decorator to decorate flask routes with. Simply add @cross_origin() below a call to Flask's @app.route(..) to allow CORS on a given route. See the full list of options in the decorator documentation.

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

Documentation

For a full list of options, please see the full documentation

Troubleshooting

If things aren't working as you expect, enable logging to help understand what is going on under the hood, and why.

logging.getLogger('flask_cors').level = logging.DEBUG

Tests

A simple set of tests is included in test/. To run, install nose, and simply invoke nosetests or python setup.py test to exercise the tests.

If nosetests does not work for you, due to it no longer working with newer python versions. You can use pytest to run the tests instead.

Contributing

Questions, comments or improvements? Please create an issue on Github, tweet at @corydolphin or send me an email. I do my best to include every contribution proposed in any way that I can.

Credits

This Flask extension is based upon the Decorator for the HTTP Access Control written by Armin Ronacher.

flask-cors's People

Contributors

aneshujevic avatar ashwani99 avatar baharev avatar bbbart avatar billbrower avatar bitdeli-chef avatar bob131 avatar celeo avatar corydolphin avatar digitizdat avatar edwardbetts avatar frantisekz avatar hugovk avatar jodiwaljay avatar joshfriend avatar kurtmckee avatar maebert avatar maximium avatar mekza avatar michalbachowski avatar pylipp avatar russelldavies avatar sachit-shroff avatar sattamjh avatar sssilver avatar sunarch avatar timgates42 avatar tirkarthi avatar tomprince avatar wking avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-cors's Issues

cannot import name CORS

Hi!
I'm having some trouble with the import. When I try
from flask.ext.cors import CORS
I have the error
ImportError: cannot import name CORS

Do you have any idea? I installed the package with the command
pip install flask-cors

setup.py error: requirements.txt not exists

 File "/tmp/pip_build_root/flask-cors/setup.py", line 18, in <module>

    with open (join(dirname(__file__), 'requirements.txt'), 'r') as f:

IOError: [Errno 2] No such file or directory: '/tmp/pip_build_root/flask-cors/requirements.txt'

It seems requirements.txt not exists on dist, I try to download it from PYPI, and requirements.txt not exists

problem when use CORS(app)

I am sorry but when I use CORS(app) I found error "Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.";

python version is 3.4.3 and flask 0.10.1;

Thanks for help.

Access-Control-Allow-Headers not working

Hello there,

Im glad i found this lib but im facing an issue, it seems like Access-Control-Allow-Headers are not being set or something.

this is my setup:

CORS(app, resources=r'/*', allow_headers='Origin, Content-Type, Accept, Authorization, X-Request-With', supports_credentials=True)

But chrome's console keeps telling me

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Am i missing something?

Im using the 2.1.2 version btw.

Add a changelog

It becomes very difficult to decide whether to upgrade without a changelog of any kind. This would definitely help us with this process.

1.10 not compatible with example app

Your example app suggests I can do something like this:

flask_app.config['CORS_RESOURCES'] = {
    r"/api/*": {
        "origins": ["http://blah.com/*", "http://foo.bar/*"]
    }
}

And indeed, in 1.9.0, I could, and life was peachy.

Upgrading to 1.10 results in origins being "*" regardless of the contents of this configuration, even when the credentials flag is set to true. As my browser immediately informed me,

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.

If there's another way I should configure origins, what is it (and can you update the example app)?

Can't intercept Flask error handlers

This doesn't currently add headers to responses created from a Flask error handler, making the error response body unreadable in some browsers.

An example of such an error handler:

@app.errorhandler(ApplicationError)
def handle_error(err):
    return err.as_response()

The resources will still send CORS headers if an error response is returned directly from the route, but not raised and handled through an error handler as shown above.

Using flask-cors with flask-security/flask-login

Hi,

I'm trying to get this work so that when I login I issue an 'Access-Control-Allow-Credentials', 'true' header. So that I can have authenticated cross-domain ajax calls. I've got a simple prototype working, but now I'm trying to get this all to work in a larger flask application using the flask-security extension.

Here's what I've tried for setting up CORS. I've also tried using @cross_origin(supports_credentials=True) on a view that also requires a login.

cors = CORS(app, resources={r"/api/*": {"origins": "*"}, r"/login": {"supports_credentials": True}})

I don't get any of the CORS headers. Here's what I see in the debug output.

DEBUG:flask.ext.cors:Enabling <function home at 0x1039e2b70> for cross_origin using options:{'supports_credentials': True}
DEBUG:runestone.cors:Request to '/login' matches CORS resource '/login'. Using options: {'origins': ['.*'], 'supports_credentials': True, 'methods': 'DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT', 'intercept_exceptions': True, 'automatic_options': True, 'send_wildcard': False, 'vary_header': True, 'allow_headers': ['.*'], 'resources': {'/api/*': {'origins': '*'}, '/login': {'supports_credentials': True}}}
DEBUG:runestone.cors:'Origin' header was not set, which means CORS was not requested, skipping
DEBUG:runestone.cors:Settings CORS headers: MultiDict([])
INFO:werkzeug:127.0.0.1 - - [22/May/2015 14:44:59] "GET /login HTTP/1.1" 302 -
DEBUG:runestone.cors:No CORS rule matches

I don't know if it matters but I have the auth stuff in a blueprint of its own.

Any ideas on where I might be going wrong? The debug output is confusing to me because it seems to recognize that I want CORS on the login, request, but then later says that CORS was not requested.

Thanks,

Brad

How can we give the allowed methods name, max age etc ?

CORS(app, resources={r"/": {"origins": ""}}, allow_headers='Content-Type', send_wildcard=True, max_age=86400, methods=['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'])

But at the browser, I am able to see only below fields -
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:15
Content-Type:application/json
Date:Wed, 04 May 2016 11:57:27 GMT

I am expecting as below-
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods:GET,POST,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:86400
Connection:keep-alive
Content-Type:application/json

Am I missing something in the CORS parameters ?

Custom exception handlers

Suppose I have:

@app.route('/doit')
@cross_origin(origins='<somewhere>')
def doit():
   raise CustomException("owch!")

@app.errorhandler(CustomException)
def handle_custom(err):
   return str(err)

Surely the expected output should be the error page with cors headers? But this is not what I find: I get an empty response with the 4xx error code and nothing else (and no stacktrace on the server).

If this is intended behavior it should be made much clearer somewhere in the docs as it confused me for a long time (though admittedly I am completely new to flask cors and http error handling). Ideally though, the expected behavior should be implemented, i.e. the error handler should check the route function to see what cors it had intended to supply and then provide them on the error response.

Using regex still requires two origins for Vary

When using a configuration like [r'https://.*\.domain'], the Vary: Origin header will never be emitted.

I think it makes sense for a regex to be treated as a list – or, indeed, just emit the header when using a list even if it's just one item long.

(also, because of certain browser bugs I'd love to have an option to always use the header for any request at any time, but that's separate.)

Support calls of abort() inside of cross_origin annotated

If I have cross_origin annotated Flask method and call abort() then CORS headers are not added to response. Not calling abort() from my methods is OK. Though some Flask plugins are using abort() function. For example Flask-Login does abort() calls.

How to allow credentialed requests

The docs mention in the first paragraph:

please see the documentation for how to enable credential'ed requests

However this is never explained

Access-Control-Allow-Methods not sent

I just updated from 1.9.0 to 1.10.2 and Access-Control-Allow-Methods is not being sent anymore. For example, the test script in this comment seems to be broken now. What I see is:

$ pip3 show flask-cors

---
Name: Flask-Cors
Version: 1.10.2
Location: /usr/local/lib/python3.4/dist-packages
Requires: Six, Flask

$ cat flask-cors-test 
from flask.ext.cors import CORS
from flask import Flask


app = Flask(__name__)
cors = CORS(app, headers="X-CSRFToken, Content-Type")

@app.route("/")
def example():
    return "Hello World!"

if __name__ == '__main__':
    with app.test_client() as c:
        for verb in ('get','options'):
            print( "Headers for %s /:\n%s" % (
                verb.upper(),
                getattr(c, verb)().headers
            ) )

$ python3.4 ./flask-cors-test 
Headers for GET /:
Content-Type: text/html; charset=utf-8
Content-Length: 12
Access-Control-Allow-Origin: *


Headers for OPTIONS /:
Content-Type: text/html; charset=utf-8
Allow: HEAD, GET, OPTIONS
Access-Control-Allow-Origin: *
Content-Length: 0


Apply CORS Based on Mimetype

I am looking for the following functionality but I'm not sure if it is possible with the way flask-cors is setup. The following code works but I would prefer to use your app if possible. Can you think of a way I can do it?

# Workaround to allow fonts (Glyphicons) to be loaded on Firefox using a CDN                        
@app.after_request                                                                                  
def add_cors_to_fonts(response):                                                                             
    mimetypes = [                                                                                   
    'application/vnd.ms-fontobject',                                                            
    'image/svg+xml',                                                                            
    'application/octet-stream',                                                                 
    'application/x-font-woff'                                                                   
]                                                                                               

if response.mimetype in mimetypes:                                                              
    response.headers['Access-Control-Allow-Origin'] = '*'                                       

return response                                   

My Unit Tests are Broken in v2

My app:

app = Flask(__name__)
cors = CORS(app)

tests:

    self.app = qp.app.test_client()

    def test_options_root(self):
        rv = self.app.options(
            '/',
            headers={
                'Access-Control-Request-Headers': 'x-amz-user-agent, x-amz-date, authorization, content-type',
                'Access-Control-Request-Method': 'POST'})
        print rv.headers

in (patched v1 and in actual v2):

Content-Type: text/html; charset=utf-8
Allow: HEAD, POST, OPTIONS, GET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Access-Control-Allow-Headers: x-amz-user-agent, x-amz-date, authorization, content-type
Content-Length: 0

in v2 tests:

Content-Type: text/html; charset=utf-8
Allow: HEAD, POST, OPTIONS, GET
Content-Length: 0

supports_credentials=False on cross_origin decorator gets interpreted incorrectly

Version: 1.10.3

myapp: INFO: attempting cors test
myapp: DEBUG: actually applying the decorator now... deca=(), deckw={'automatic_options': True, 'supports_credentials': False, 'allow_headers': ['Content-Type']}, a=(), kw={}
myapp: DEBUG: Hey there... request method is OPTIONS
Flask-Cors: DEBUG: Request to '/corstests/test3' is enabled for CORS with options:{'origins': ['^(?i)https://.*\\.REDACTED.com$'], 'vary_header': True, 'methods': 'DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT', 'send_wildcard': True, 'supports_credentials': 'False', 'allow_headers': 'Content-Type', 'automatic_options': True, 'origins_str': '', 'always_send': True}
Flask-Cors: DEBUG: CORS request received with 'Origin' https://app.local.REDACTED.com
Flask-Cors: DEBUG: Given origin matches set of allowed origins
Flask-Cors: INFO: CORS request from Origin:https://app.local.REDACTED.com, setting Access-Control-Allow-Origin:https://app.local.REDACTED.com
Flask-Cors: DEBUG: Settings CORS headers: {'Access-Control-Allow-Methods': 'DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT', 'Vary': 'Origin', 'Allow': u'POST, OPTIONS', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': u'https://app.local.REDACTED.com', 'Access-Control-Allow-Headers': 'Content-Type', 'Content-Type': u'text/html; charset=utf-8'}

Explanation of debug log: I am not applying the decorator at start up time but at call time. I don't think this is the issue. I am sending supports_credentials=False kwarg to the cross_origin decorator and the above log is what happens when I make an OPTIONS preflight request in my unit tests. I think the root cause is _serialize_option function stringifying the boolean value which then becomes 'False' which is treated as a true value when used in a boolean context to determine what behaviour to use.

I have not tested if this works properly in 2.x.

Passing a Flask blueprint to CORS constructor fails

Attempting to pass a blueprint object to the flask.ext.cors.CORS results in the following traceback

  File "/usr/lib/python3.4/site-packages/flask_cors/extension.py", line 59, in __init__
    self.init_app(app, **kwargs)
  File "/usr/lib/python3.4/site-packages/flask_cors/extension.py", line 64, in init_app
    options = get_cors_options(app, self._options, kwargs)
  File "/usr/lib/python3.4/site-packages/flask_cors/core.py", line 263, in get_cors_options
    options.update(get_app_kwarg_dict(appInstance))
  File "/usr/lib/python3.4/site-packages/flask_cors/core.py", line 278, in get_app_kwarg_dict
    for k in CONFIG_OPTIONS
  File "/usr/lib/python3.4/site-packages/flask_cors/core.py", line 279, in <genexpr>
    if app.config.get(k) is not None
AttributeError: 'Blueprint' object has no attribute 'config'

Drops multiple headers, like Set-Cookie

Hi. I'm using this plugin and have discovered a problem. It seems that whatever it does, to modify the headers, it truncates headers with the same name.

I am using flask's set cookie function, which creates multiple entries for Set-Cookie header. However, if I apply the @cross_origin operator on a route method, it drops all but one of Set-Cookie headers.

Disable logging

Is there a way to disable flask-cors logging? Logging is good for testing but it becomes noise when the app is up and running.

preflighted OPTIONS request return non-200

If my app has a before_request hook returns 401 to client:

@app.before_request
def require_login():
    flask.abort(401)

than the preflighted OPTIONS request always yield 401 too, as extra auth headers rely on the response of preflighted request ...
Shouldn't it alway return 200?

using flask-cors==2.1.2

Cannot load CORS content

Hello, I happened across your project after banging my head against trying to make an XMLHttpRequest in my javascript against my flask code (running on the same server, ports 8000 and 5000, respectively). No matter what I try, nothing gets past the "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access." error. From flask:

8 from flask.ext.cors import cross_origin
...
39 @app.route('/character_scrape', methods=['GET', 'POST'])
40 @cross_origin(headers=['Content-Type'])
41 @on_subnet
42 def scrape_char():

Thanks for your time!

Long time responding

On ajax cross domain request flask respond after a long time . For example 10 seconds.
If I call url from browser it respond fastly, but with cors and on ajax request flask wait a long time.
I'm working on localhost.

Can you put the decorator on a @before_request function?

Can you put the decorator on a @before_request function?
I'm using Flask-HTTPAuth and serving JSON.

When I do I get the error "ValueError: View function did not return a response"

Here is how I am using it.
https://github.com/Siecje/flasky/blob/master/app/api_1_0/authentication.py
If you run the tests in the repo (python manage.py test) you will see the error message.

Traceback (most recent call last):
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1473, in full_dispatch_request
    rv = self.preprocess_request()
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1666, in preprocess_request
    rv = func()
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask_httpauth.py", line 53, in decorated
    return f(*args, **kwargs)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask_cors.py", line 119, in wrapped_function
    resp = make_response(f(*args, **kwargs))
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/helpers.py", line 183, in make_response
    return current_app.make_response(args)
  File "/home/siecje/Desktop/wr-ccafe/venv/lib/python2.7/site-packages/flask/app.py", line 1566, in make_response
    raise ValueError('View function did not return a response')
ValueError: View function did not return a response

Regular expression or wildcard origins

Is there any way to specify origins in a regular expression, so that urls matching the pattern are allowed? Eg: all subdomains from a given domain.. r"https?://\w*\.?example\.com:?\d*/?.*"

Unable to Implement 'Content-Type' Header.

Using flask-cors 1.1.1 installed via pip, adding @cross_origin(headers='Content-Type') to a particular app route does not result in Content-Type being returned as part of Access-Control-Allow-Headers.

Response headers solely consist of the following:

HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 671
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, HEAD, OPTIONS, POST, PUT
Server: Werkzeug/0.9.4 Python/2.6.6

Secure defaults

Let's be secure by default.

  • Don't send headers if Origin not in request
  • Default to only allowing idempotent verbs
  • Tell people that CSRF is a thing
  • Release v2.0.0 as it will change defaults and is not backwards compatible.

Support default configuration for all parameters

Would anyone else find it useful to allow configuration of default parameters for all options?

Currently, CORS_ORIGINS is supported as a flask configuration option, would adding the other params be useful for others, or just add cruft?

headers not being set or set to nonsense

I am working with blueprints and importing my views after settings CORS(blueprint).
I have tried using just defaults and settings options. Both are just like this, though, I often don't even get the Access-Control-Allow-Origin header if I set any options at all.
No matter how I slice it, I seem to get a response of either this from httpie:
HTTP/1.0 200 OK
Allow: POST, HEAD, OPTIONS, GET
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Wed, 16 Mar 2016 20:42:15 GMT
Server: Werkzeug/0.11.2 Python/2.7.10

Which doesn't have any of the headers.
or from Postman:
Access-Control-Allow-Origin →file://
Allow →POST, HEAD, OPTIONS, GET
Content-Length →0
Content-Type →text/html; charset=utf-8
Date →Wed, 16 Mar 2016 20:42:24 GMT
Server →Werkzeug/0.11.2 Python/2.7.10

DELETE not working?

I was able to successfully send GET, POST, and PUT requests via CORS, but i'm having problems with DELETE.

I already posted a question on stackoverflow, http://stackoverflow.com/questions/25358368/cant-delete-when-post-put-and-get-works-angularjs-cors-flask-cors. If you wanna see the details,

and one of the guys suggested it might be an issue with flask-cors, since we both notice on your ALL_METHODS = ['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT'], delete was not mentioned.

was this intentional? , i'm kinda new on python and more so with flask., and i, really at a loss on how come its not working with delete when all others does.

Need 'Access-Control-Allow-Credentials' header

Here is my case:

Client post username and password to server, after authentication,
Server send header "Authorization" with auth token to client, then client save the token.
Client and server is not in the same domain, so I need CORS.

server code:

    from flask.ext.cors import CORS
    CORS(app)

But it cause 'Refused to get unsafe header "Authorization"'

    // xhr is response object
    xhr = XMLHttpRequest {}, key = "Authorization"
    xhr.getResponseHeader(key); // error

Then I set:

    req.withCredentials=true

Then error:

    XMLHttpRequest cannot load http://www.xxxx.cn/api/user/login. Credentials flag is 'true',        but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin   'http://127.0.0.1:5000' is therefore not allowed access.

I find a clue on http://stackoverflow.com/questions/24687313/what-exactly-does-the-access-control-allow-credentials-header-do

So, it need 'Access-Control-Allow-Credentials' header

Version 3.0.0 Release?

Just wanted to check in and see if there was a time frame for when version 3.0.0 will be released?

I noticed some changes to the code within the past month, specifically send_always, that appears to resolve an issue I am experiencing.

Thanks!

“No 'Access-Control-Allow-Origin' header” error in POST with OPTIONS Pre-flight

I'm getting a “No 'Access-Control-Allow-Origin' header” error on my POST request following a 200 ok OPTIONS request. I have the line cors = CORS(app) in my flask (0.10.1) app.

OPTIONS response headers

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: POST, OPTIONS
Access-Control-Allow-Origin: http://localhost:7000
Access-Control-Allow-Headers: accept, content-type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Content-Length: 0
Server: Werkzeug/0.11.3 Python/2.7.11
Date: Wed, 18 May 2016 01:08:25 GMT

OPTIONS request headers

OPTIONS /testPost HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: POST
Origin: http://localhost:7000
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://localhost:7000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

POST response headers

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html; charset=utf-8
X-XSS-Protection: 0
Connection: close
Server: Werkzeug/0.11.3 Python/2.7.11
Date: Wed, 18 May 2016 01:08:25 GMT

POST request headers

POST /testPost HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Content-Length: 22
Accept: application/json, text/plain, */*
Origin: http://localhost:7000
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:7000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

Allow headers doesn't works

I've created this small rest api application

from flask import Flask
from flask.ext.cors import CORS
from flask.ext.restful import Resource, Api
import json
app = Flask(__name__)
CORS(app, resources=r'/api/*', allow_headers='Content-Type')
api = Api(app)

workplaces = [
    {"id":1, "name":"zob", "location":{"latitude": 47.099, "longitude": 2.438}}
]


class WorkplaceList(Resource):
    def get(self):
        return workplaces

class Index(Resource):
    def get(self):
        return "ok"

api.add_resource(Index, '/')
api.add_resource(WorkplaceList, '/api/workplace')

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

When I send request to this small sever, there is no Access-Control-Allow-Header HTTP header :

[tlk:~/Dev/TmpRestAPI]$ curl -X GET http://localhost:5000/api/workplace -i
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 154
Access-Control-Allow-Origin: *
Server: Werkzeug/0.9.6 Python/2.7.9
Date: Wed, 07 Jan 2015 07:44:51 GMT

[
    {
        "id": 1, 
        "location": {
            "latitude": 47.099, 
            "longitude": 2.438
        }, 
        "name": "zob"
    }
]
[tlk:~/Dev/TmpRestAPI]$ curl -X OPTIONS http://localhost:5000/api/workplace -i
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: HEAD, OPTIONS, GET
Access-Control-Allow-Origin: *
Content-Length: 0
Server: Werkzeug/0.9.6 Python/2.7.9
Date: Wed, 07 Jan 2015 07:45:11 GMT

Issue with functools.partial in 1.10.0 using Python 2.7.9

When upgrading to 1.10.0 in environment with Python 2.7.0 following exception is thrown:

File "/Users/joonathan/Development/App/application/app.py", line 61, in create_app
configure_extensions(app)
File "/Users/joonathan/Development/App/application/app.py", line 98, in configure_extensions
cors.init_app(app)
File "/Users/joonathan/.virtualenvs/App/lib/python2.7/site-packages/flask_cors.py", line 274, in init_app
app.handle_exception)
File "/Users/joonathan/.virtualenvs/App/lib/python2.7/site-packages/flask_cors.py", line 267, in _after_request_decorator
@wraps(f)
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'functools.partial' object has no attribute 'module'

Setting comma separated `Access-Control-Allow-Origin` values is not supported by FireFox.

Using version 2.1.2, initialising using:

....
from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)
....

When making an AJAX request from a local machine on a non-standard port to an external server serving the above code running Flask 0.10.1 on Apache with mod_wsgi, the server responds with Access-Control-Allow-Origin: "http://localhost:8080, *". Such comma separated lists are not supported by FireFox, and gives the following error in the JavaScript debugging console: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://hostna.me/app/route. (Reason: CORS header 'Access-Control-Allow-Origin' does not match 'http://localhost:8080, *').

Can't get OPTIONS pre-flight to work

Hi,

I'm getting a OPTIONS request from the browser as expected, but Flask returns 404 immediately.
I've got the "@cross_origin' decoration on my route.
I've got:
app.config['CORS_ORIGINS'] = ['http://localhost:9000']
app.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']
app.config['CORS_AUTOMATIC_OPTIONS'] = True

What am I doing wrong?

Thanks,
Eric

CORS with blueprint

with code:

bp = flask.Blueprint('api', __name__, url_prefix='/api')
bp = flask_cors.CORS(bp, max_age=30*86400)

@bp.before_request
def load_user():
    ...

will yield:

E   AttributeError: 'CORS' object has no attribute 'before_request'

my usage is wrong or a bug?

Cross Origin Issue in Flask in spite of using flask

I'm getting Cross Origin issue in flask inspite of using CORS, here is the small webservice:

from flask import Flask,request
import json
from flask.ext.cors import CORS
app = Flask(name)
CORS(app, resources='*', allow_headers='Content-Type')
cars = [{'color': 'red', 'brand': 'BMW', 'plateNumber': '567hghh', 'id': 1}, {'color': 'blue', 'brand': 'Ford', 'plateNumber': '6776hhgd', 'id': 2}, {'color': 'red', 'brand': 'BMW', 'plateNumber': '6887hhgd', 'id': 3}]
@app.route("/cars",methods=['POST','OPTIONS'])
def POST_cars():
args = json.loads(request.data)
newCar = {}
newCar['color'] = args['color']
newCar['brand'] = args['brand']
newCar['plateNumber'] = args['plateNumber']
newCar['id'] = len(cars)
return_obj = {}
return_obj['car'] = newCar
cars.append(newCar)
return str(json.dumps(return_obj))

I'm getting the error with the following call:

$.post( "http://127.0.0.1:5000/cars", {
"color": "red",
"brand": "BMW",
"plateNumber": "567hghh"
} );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.