lwcolton / falcon-cors Goto Github PK
View Code? Open in Web Editor NEWCORS support for Falcon: http://falconframework.org
License: Apache License 2.0
CORS support for Falcon: http://falconframework.org
License: Apache License 2.0
This would help a lot with #1
Deprecation warnings are raised due to invalid escape sequences. This can be fixed by using raw strings or escaping the literals. pyupgrade also helps in automatic conversion : https://github.com/asottile/pyupgrade/
find . -iname '*.py' | grep -Ev 'vendor|example|doc|sphinx' | xargs -P4 -I{} python3.8 -Wall -m py_compile {}
./tests/test_cors.py:199: DeprecationWarning: invalid escape sequence \.
cors = CORS(allow_origins_regex='rack.*\.com')
./tests/test_cors.py:223: DeprecationWarning: invalid escape sequence \.
allow_origins_regex='rack.*\.com'
./tests/test_cors.py:387: DeprecationWarning: invalid escape sequence \.
allow_credentials_origins_regex='.*\.rackspace\..*'
./tests/test_cors.py:401: DeprecationWarning: invalid escape sequence \.
allow_credentials_origins_regex='.*\.rackspace\..*'
Hi.
What's the story with falcon-cors on Python 3? You probably already know that 2.x is not going to be supported much longer. I'm asking because caniusepython3 identified falcon-cors as one of the projects that need to be looked at.
If the compatibility is as yet unknown, is there a decent test suite I can try with a 3.x interpreter?
Thanks!
Hi there,
maybe you could help me on this one:
https://stackoverflow.com/questions/56172533/micro-services-using-falcon-managing-cors
Any remarks, questions, do not hesitate!
And thanks in advance for your help!
J
Hi @lwcolton, someone posted a question to the Falcon group regarding falcon-cors. Would you mind taking a look? Thanks!
https://groups.google.com/forum/#!topic/falconframework/whco-MaynE4
Any usage breaks the entire API.
I have the following setup
falcon==1.3.0
falcon-cors==1.1.7
gunicorn==19.7.1
json-logging-py==0.2
I am able to specify the "allow_origins_list" for localhost, but when I attempt to use a VM, the IP address is not constant and is sometimes different when accessed outside the corporate network.
If I attempt to add the allow_all_origins header into the CORS call, the app is unresponsive and will not accept any connections. The same thing occurs if I try to place a wildcard into the allow_origins_list.
I also cannot place the cors=public_cors
call within any of my Resource objects. If I add a cors variable that links to the CORS()
call at all, I can't make a connection to any of the Resource objects. Even if the IPs are listed in the allow_origins_list.
Here are the needed excerpts of code:
`
""" Falcon CORS for external testing and external access """
from falcon_cors import CORS
...
public_cors = CORS(allow_origins_list=['http://localhost:3000'],
allow_all_headers=True,
allow_all_methods=True)
...
class AuthDataResource:
""" Falcon Authentication Resource """
This is where if I try to add cors=public_cors I cannot access this or any other resource
def on_get(self, req, res):
""" Handle incoming GET requests, return relevant info """
json = {
'version': VERSION,
'status': falcon.HTTP_200
}
logger.info(req)
res.media = json
res.status = falcon.HTTP_200
logger.info(res)
...
API = application = falcon.API(middleware=[cors.middleware])
API.add_route('/api/v1/version', AuthDataResource())
API.add_route('/api/v1/auth', APIAuthenticationResource())
API.add_route('/api/v1/ui/auth', BasicAuthenticationResource())
API.add_route('/api/v1/auth/getToken', GetTokenAuthenticationResource())
`
I'm just really lost and the documentation or issues don't not anything like this. I'm building out a pretty decent sized API and I love using falcon, but this is a huge hang-up so far.
Hi,
I'm using the falcon-cors middleware but I still get :
Fetch API cannot load http://10.0.0.113/api/users/. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I configured the api that all headers are allowed :
import falcon
from falcon_cors import CORS
cors = CORS(allow_all_origins=True, allow_all_headers=True)
....
api = falcon.API(before=[auth], middleware=[cors.middleware])
....
and here my post method :
...
def on_post(self, req, resp):
attributes = json.loads(req.stream.read())
user = User({})
user.set_json_attributes(attributes)
db_session.add(user)
try:
db_session.commit()
except:
db_session.rollback()
raise
resp.status = falcon.HTTP_200
resp.body = json.dumps({'user': user.json_attributes()})
...
What do I do wrong? Here you can find a curl from my api call :
curl 'http://10.0.0.113/api/users/' -X OPTIONS -H 'Pragma: no-cache' -H 'Access-Control-Request-Method: POST' -H 'Origin: http://localhost:3000' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8,es;q=0.6,fr;q=0.4,nl;q=0.2' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36' -H 'Accept: /' -H 'Cache-Control: no-cache' -H 'Referer: http://localhost:3000/users/add' -H 'Connection: keep-alive' -H 'Access-Control-Request-Headers: accept, content-type' --compressed
Great seeing all the tests and CI hooked up. Consider adding code coverage analysis & badge? Coveralls is popular. I have also found http://codecov.io/ a good option.
Hello, I ran into a problem similar to #1 while sending a POST
request to my Falcon API from an Angular web app.
After Googling around a bit and finding this StackOverflow question, I realized the browser was first sending an OPTIONS
request, and complaining about not getting an Access-Control-Allow-Headers
header back.
I had set allow_all_headers=True
, but still the API was not returning the Access-Control-Allow-Headers
header in response to the OPTIONS
request. I eventually fixed this by defining a new on_options
method on the resource, but this seems pretty clunky. Shouldn't that be the expected behavior when setting allow_all_headers=True
? Perhaps falcon-cors
is not even seeing that OPTIONS
request that precedes the POST
request?
Didn't work:
cors = CORS(allow_origins_list=['http://localhost:4200'], allow_all_headers=True)
app = falcon.API(middleware=[cors.middleware])
Did work:
def on_options(self, req, resp):
log.debug("OPTIONS /login")
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
Hello! Thanks for your work.
I build SPA with React.js and Falcon. Frontend created by create-react-app
CLI.
Here is my ./api/__init__.py
:
import falcon
from falcon_cors import CORS
from api.views import UserResource
cors = CORS(
allow_all_origins=True,
allow_credentials_all_origins=True,
allow_all_headers=True,
log_level='DEBUG'
)
# Init app
app = falcon.API(middleware=[cors.middleware])
# API routes
app.add_route('/api/user', UserResource())
...and my ./api/views.py
is:
import json, datetime
from falcon import HTTP_404
from peewee import IntegrityError
from playhouse.shortcuts import model_to_dict
from api.models import Users
from api.utils import str_converter
class UserResource(object):
"""
User endpoint
Methods: GET
"""
# Show User by UUID
def on_get(self, req, resp):
try:
# Build user query
user = Users.get(Users.uuid == req.media.get('uuid'))
# Return JSON with user object
resp.body = json.dumps({
"data": model_to_dict(user),
"status": "success",
"description": None
}, default=str_converter)
except Users.DoesNotExist:
# Return JSON with error (404)
resp.status = HTTP_404
resp.body = json.dumps({
"data": None,
"status": "error",
"description": "User does not exists!"
})
./frontend/src/App.js
:
import React, {Component} from 'react';
import axios from 'axios';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
users: []
};
}
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/user', {
data: {
id: 1
}
}).then(
(result) => {
this.setState({
isLoaded: true,
users: result.data.data
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
});
}
render() {
const {error, isLoaded, users} = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{users.map(user => (<li key={user.uuid}>{user.first_name} {user.last_name}</li>))}
</ul>
</div>
);
}
}
};
When I run this application (front and back):
$ gunicorn --reload api:app
$ npm start
On Google Chrome console I see this error:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/user' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
Why? What I did wrong way? Please help me...
When I register a resource with a suffix specified in the add_route
call, preflight requests to that resource fail with Aborting response due to unallowed method because _get_resource_methods
returns an empty list.
Setting allow_all_methods=True
does not help, each request is still checked against the list of methods on the resource.
The example in this gist illustrates the problem. When you run it, it outputs:
Without: ['GET', 'POST']
With suffix: []
Making a CORS POST to /a
succeeds, while the same request to /b
fails with the unallowed method message.
falcon-cors/src/falcon_cors/log.py
Line 6 in 9e12438
propogate
should be propagate
. PR inbound.
Hello,
I'm getting this error from falcon_cors :
Aborting response due to origin not allowed
I'm not sure yet but I suspect that the user is using a VPN.
The request is still processed even with origin not allowed, just there is no success response. Is this a normal behavior ?
Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.