Python flask_cors.CORS Examples

The following are 16 code examples of flask_cors.CORS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_cors , or try the search function .
Example #1
Source File: app.py    From MAX-Framework with Apache License 2.0 6 votes vote down vote up
def __init__(self, title=API_TITLE, desc=API_DESC, version=API_VERSION):
        self.app = Flask(title, static_url_path='')

        # load config
        if os.path.exists("config.py"):
            self.app.config.from_object("config")

        self.api = Api(
            self.app,
            title=title,
            description=desc,
            version=version)

        self.api.namespaces.clear()
        self.api.add_namespace(MAX_API)

        # enable cors if flag is set
        if os.getenv('CORS_ENABLE') == 'true' and \
                (os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or self.app.debug is not True):
            CORS(self.app, origins='*')
            print('NOTE: MAX Model Server is currently allowing cross-origin requests - (CORS ENABLED)') 
Example #2
Source File: app.py    From dribdat with MIT License 6 votes vote down vote up
def init_app(config_object=ProdConfig):
    """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.

    :param config_object: The configuration object to use.
    """
    app = Flask(__name__)
    app.config.from_object(config_object)

    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    app.config['CORS_HEADERS'] = 'Content-Type'

    register_extensions(app)
    register_blueprints(app)
    register_oauthhandlers(app)
    register_errorhandlers(app)
    register_filters(app)
    register_loggers(app)
    register_shellcontext(app)
    register_commands(app)
    return app 
Example #3
Source File: __init__.py    From Reseed-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_app(debug=False):
    """Create an application."""
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile('config.py')
    app.debug = debug

    from .reseed import reseed
    from .plugin import plugin
    from .user import us
    app.register_blueprint(us)
    app.register_blueprint(reseed)
    app.register_blueprint(plugin)

    # fixme: edit CORS
    cors.init_app(app)
    socketio.init_app(app, cors_allowed_origins='*')
    limiter.init_app(app)
    login_manager.init_app(app)
    mysql.init_app(app)
    redis.init_app(app)

    return app 
Example #4
Source File: app.py    From biggraphite with Apache License 2.0 6 votes vote down vote up
def initialize_api(self):
        """Initialize an API."""
        blueprint = flask.Blueprint("api", __name__, url_prefix="/api")

        api = flask_restplus.Api(version="1.0", title="BigGraphite API")
        api.namespaces = []
        api.add_namespace(ns_bgutil.api)
        api.add_namespace(ns_biggraphite.api)
        api.init_app(blueprint)

        self.app.register_blueprint(blueprint)

        if flask_cors:
            # Allow others to request swagger stuff without restrictions.
            # This helps for https reverse proxy with bad headers.
            flask_cors.CORS(
                self.app, resources={r"/api/swagger.json": {"origins": "*"}}) 
Example #5
Source File: server.py    From mrisa with GNU General Public License v2.0 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Meta Reverse Image Search API')
    parser.add_argument('-p', '--port', type=int, default=5000, help='port number')
    parser.add_argument('-d','--debug', action='store_true', help='enable debug mode')
    parser.add_argument('-c','--cors', action='store_true', default=False, help="enable cross-origin requests")
    parser.add_argument('-a', '--host', type=str, default='0.0.0.0', help="sets the address to serve on")
    args = parser.parse_args()

    if args.debug:
        app.debug = True

    if args.cors:
        CORS(app, resources=r'/search/*')
        app.config['CORS_HEADERS'] = 'Content-Type'

        global search
        search = cross_origin(search)
        print(" * Running with CORS enabled")


    app.run(host=args.host, port=args.port) 
Example #6
Source File: server.py    From aw-server with Mozilla Public License 2.0 6 votes vote down vote up
def _config_cors(cors_origins: List[str], testing: bool):
    if cors_origins:
        logger.warning('Running with additional allowed CORS origins specified through config or CLI argument (could be a security risk): {}'.format(cors_origins))

    if testing:
        # Used for development of aw-webui
        cors_origins.append("http://127.0.0.1:27180/*")

    # TODO: This could probably be more specific
    #       See https://github.com/ActivityWatch/aw-server/pull/43#issuecomment-386888769
    cors_origins.append("moz-extension://*")

    # See: https://flask-cors.readthedocs.org/en/latest/
    CORS(current_app, resources={r"/api/*": {"origins": cors_origins}})


# Only to be called from aw_server.main function! 
Example #7
Source File: server.py    From cwg with GNU General Public License v3.0 6 votes vote down vote up
def main(argv):
    global MAKEMEAHANZI_PATH, CEDICT_PATH;
    opts, args = getopt.getopt(argv, '', ['makemeahanzi=', 'cedict=']);
    for opt, arg in opts:
        if opt == '--makemeahanzi':
            MAKEMEAHANZI_PATH = arg;
        elif opt == '--cedict':
            CEDICT_PATH = arg;
    if MAKEMEAHANZI_PATH == '' or CEDICT_PATH == '':
        usage();
        exit(1);

    app = Flask(__name__);
    cors = CORS(app);
    app.config['CORS_HEADERS'] = 'Content-Type';
    api = Api(app);
    api.add_resource(GenerateInfos, '/generate_infos');
    api.add_resource(GenerateSheet, '/generate_sheet');
    api.add_resource(RetrieveSheet, '/retrieve_sheet');
    api.add_resource(RetrieveCount, '/retrieve_count');
    app.run(port='5002', threaded=True); 
Example #8
Source File: manage.py    From C-3PO with MIT License 5 votes vote down vote up
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    LOG.info("app loaded with configuration {}!".format(config_name))

    CORS(app)
    LOG.info("Flask CORS setup successfully")
    with app.app_context():
        register_blueprints(app)
    return app 
Example #9
Source File: api.py    From comet-core with Apache License 2.0 5 votes vote down vote up
def create_app(self):
        """Create a Flask app from the configured instance

        Returns:
            Flask: the Flask (uwsgi) app
        """
        app = Flask(__name__)

        app.config["auth_func"] = self.auth_func
        app.config["hydrator_func"] = self.hydrator_func
        app.config["request_hydrator_func"] = self.request_hydrator_func
        app.config["database_uri"] = self.database_uri
        app.config["hmac_secret"] = self.hmac_secret

        cors = CORS()
        cors.init_app(app, resources={r"/*": {"origins": self.cors_origins, "supports_credentials": True}})

        app.register_blueprint(api_v0.bp)

        @app.route("/")
        def health_check():  # pylint: disable=unused-variable
            """Can be called by e.g. Kubernetes to verify that the API is up

            Returns:
                str: the static string "Comet-API", could be anything
            """
            return "Comet-API"

        return app 
Example #10
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_origin(self, origin):
        """
        Overridden function from WebSocketHandler for CORS policy.
        This ensures that websocket connection can be made from any
        origin.
        """
        return True 
Example #11
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self,
                 name,
                 server_base=constants.ORIGAMI_SERVER_BASE_URL,
                 cache_path=constants.GLOBAL_CACHE_PATH):
        """
        Inits class with provided arguments
        """

        self.app_name = name
        self.origami_server_base = server_base
        # self.token = validate_token(token)
        # self.target = parse_target(token)

        self.server = Flask(__name__)
        self.cors = CORS(self.server) 
Example #12
Source File: build.py    From code-coverage with Mozilla Public License 2.0 5 votes vote down vote up
def build_flask_app(project_name, app_name, openapi):
    """
    Create a new Flask backend application
    app_name is the Python application name, used as Flask import_name
    project_name is a "nice" name, used to identify the application
    """
    assert os.path.exists(openapi), "Missing openapi file {}".format(openapi)
    logger.debug("Initializing", app=app_name, openapi=openapi)

    # Start OpenAPI app
    app = connexion.App(import_name=app_name)
    app.name = project_name
    app.add_api(openapi)

    # Enable security
    security = flask_talisman.Talisman()
    security.init_app(app.app, **TALISMAN_CONFIG)

    # Enable wildcard CORS
    cors = flask_cors.CORS()
    cors.init_app(app.app, origins=["*"])

    # Add exception Json renderer
    for code, exception in werkzeug.exceptions.default_exceptions.items():
        app.app.register_error_handler(exception, handle_default_exceptions)

    # Redirect root to API
    app.add_url_rule(
        "/", "root", lambda: flask.redirect(app.options.openapi_console_ui_path)
    )

    # Dockerflow checks
    app.add_url_rule("/__heartbeat__", view_func=heartbeat_response)
    app.add_url_rule("/__lbheartbeat__", view_func=lbheartbeat_response)
    app.add_url_rule("/__version__", view_func=get_version)

    logger.debug("Initialized", app=app.name)
    return app 
Example #13
Source File: controller_inject.py    From ibeis with Apache License 2.0 4 votes vote down vote up
def get_flask_app(templates_auto_reload=True):
    # TODO this should be initialized explicity in main_module.py only if needed
    global GLOBAL_APP
    global GLOBAL_CORS
    global GLOBAL_CAS
    global HAS_FLASK
    if not HAS_FLASK:
        print('flask is not installed')
        return None
    if GLOBAL_APP is None:
        if hasattr(sys, '_MEIPASS'):
            # hack for pyinstaller directory
            root_dpath = sys._MEIPASS
        else:
            root_dpath = abspath(dirname(dirname(__file__)))
        tempalte_dpath = join(root_dpath, 'web', 'templates')
        static_dpath = join(root_dpath, 'web', 'static')
        if ut.VERBOSE:
            print('[get_flask_app] root_dpath = %r' % (root_dpath,))
            print('[get_flask_app] tempalte_dpath = %r' % (tempalte_dpath,))
            print('[get_flask_app] static_dpath = %r' % (static_dpath,))
            print('[get_flask_app] GLOBAL_APP_NAME = %r' % (GLOBAL_APP_NAME,))
        GLOBAL_APP = flask.Flask(GLOBAL_APP_NAME,
                                 template_folder=tempalte_dpath,
                                 static_folder=static_dpath)

        if ut.VERBOSE:
            print('[get_flask_app] USING FLASK SECRET KEY: %r' % (GLOBAL_APP_SECRET, ))
        GLOBAL_APP.secret_key = GLOBAL_APP_SECRET

        if templates_auto_reload:
            GLOBAL_APP.config['TEMPLATES_AUTO_RELOAD'] = True
        GLOBAL_APP.QUERY_OBJECT = None
        GLOBAL_APP.QUERY_OBJECT_JOBID = None
        GLOBAL_APP.QUERY_OBJECT_FEEDBACK_BUFFER = []
        GLOBAL_APP.GRAPH_CLIENT_DICT = {}

        if HAS_FLASK_CORS:
            GLOBAL_CORS = CORS(GLOBAL_APP, resources={r"/api/*": {"origins": "*"}})  # NOQA
        if HAS_FLASK_CAS:
            GLOBAL_CAS = CAS(GLOBAL_APP, '/cas')
            GLOBAL_APP.config['SESSION_TYPE']    = 'memcached'
            GLOBAL_APP.config['SECRET_KEY']      = GLOBAL_APP_SECRET
            GLOBAL_APP.config['CAS_SERVER']      = 'https://cas-auth.rpi.edu'
            GLOBAL_APP.config['CAS_AFTER_LOGIN'] = 'root'
    return GLOBAL_APP

# try and load flask 
Example #14
Source File: app.py    From fastlane with MIT License 4 votes vote down vote up
def create_app(self, testing):
        self.app = Flask("fastlane")

        self.testing = testing
        self.app.testing = testing
        self.app.error_handlers = []

        for key in self.config.items.keys():
            self.app.config[key] = self.config[key]

        self.app.config["ENV"] = self.config.ENV
        self.app.config["DEBUG"] = self.config.DEBUG
        self.app.original_config = self.config
        self.app.log_level = self.log_level
        self.configure_logging()
        self.connect_redis()
        self.configure_queue()
        #  self.connect_queue()
        self.config_blacklist_words_fn()

        self.configure_basic_auth()
        self.connect_db()
        self.load_executor()
        self.load_error_handlers()

        enable_cors = self.app.config["ENABLE_CORS"]

        if (
            isinstance(enable_cors, (str, bytes)) and enable_cors.lower() == "true"
        ) or (isinstance(enable_cors, (bool)) and enable_cors):
            origin = self.app.config["CORS_ORIGINS"]
            self.app.logger.info(f"Configured CORS to allow access from '{origin}'.")
            CORS(self.app)

        metrics.init_app(self.app)
        self.app.register_blueprint(metrics.bp)
        self.app.register_blueprint(healthcheck)
        self.app.register_blueprint(enqueue)
        self.app.register_blueprint(task_api)
        self.app.register_blueprint(execution_api)
        self.app.register_blueprint(status)
        self.app.register_blueprint(routes_api)

        self.app.register_blueprint(gzipped.bp)
        gzipped.init_app(self.app)

        sockets = Sockets(self.app)
        sockets.register_blueprint(stream) 
Example #15
Source File: __main__.py    From sandman2 with Apache License 2.0 4 votes vote down vote up
def main():
    """Main entry point for script."""
    parser = argparse.ArgumentParser(
        description='Auto-generate a RESTful API service '
        'from an existing database.'
        )
    parser.add_argument(
        'URI',
        help='Database URI in the format '
             'postgresql+psycopg2://user:password@host/database')
    parser.add_argument(
        '-d',
        '--debug',
        help='Turn on debug logging',
        action='store_true',
        default=False)
    parser.add_argument(
        '-p',
        '--port',
        help='Port for service to listen on',
        default=5000)
    parser.add_argument(
        '-l',
        '--local-only',
        help='Only provide service on localhost (will not be accessible'
             ' from other machines)',
        action='store_true',
        default=False)
    parser.add_argument(
        '-r',
        '--read-only',
        help='Make all database resources read-only (i.e. only the HTTP GET method is supported)',
        action='store_true',
        default=False)
    parser.add_argument(
        '-s',
        '--schema',
        help='Use this named schema instead of default',
        default=None)

    parser.add_argument(
        '-e',
        '--enable-cors',
        help='Enable Cross Origin Resource Sharing (CORS)',
        default=False)


    args = parser.parse_args()
    app = get_app(args.URI, read_only=args.read_only, schema=args.schema)
    if args.enable_cors:
        from flask_cors import CORS
        CORS(app)
     if args.debug:
        app.config['DEBUG'] = True
    if args.local_only:
        host = '127.0.0.1'
    else:
        host = '0.0.0.0'
    app.config['SECRET_KEY'] = '42'
    app.run(host=host, port=int(args.port)) 
Example #16
Source File: ext.py    From hepdata with GNU General Public License v2.0 4 votes vote down vote up
def setup_app(self, app):

        try:
            from flask_cors import CORS
            pkg_resources.get_distribution('Flask-CORS')

            # CORS can be configured using CORS_* configuration variables.
            CORS(app)

        except pkg_resources.DistributionNotFound:
            raise RuntimeError(
                "You must use `pip install flask-cors` to "
                "enable CORS support.")

        @app.context_processor
        def is_coordinator_or_admin():
            """
                Determines if the user is an admin or coordinator given their
                assigned accRoles.

                :return: true if the user is a coordinator or administrator,
                false otherwise
            """
            result = user_is_admin_or_coordinator(current_user)
            return dict(
                user_is_coordinator_or_admin=result)

        @app.context_processor
        def is_admin():
            """
                Determines if the user is an admin given their
                assigned accRoles.

                :return: true if the user is an administrator,
                false otherwise
            """
            result = user_is_admin(current_user)
            return dict(user_is_admin=result)

        @app.context_processor
        def show_dashboard():
            """
            Determines if a user should be able to see the submission overview page.

            :return:
            """
            if current_user and current_user.is_authenticated:
                if user_is_admin_or_coordinator(current_user):
                    return dict(show_dashboard=True)
                else:
                    id = int(current_user.get_id())
                    with db.session.no_autoflush:
                        submissions = SubmissionParticipant.query.filter(
                            SubmissionParticipant.user_account == id).count()

                    return dict(show_dashboard=submissions > 0)

            return dict(show_dashboard=False)