當前位置: 首頁>>代碼示例>>Python>>正文


Python flask_cors.CORS屬性代碼示例

本文整理匯總了Python中flask_cors.CORS屬性的典型用法代碼示例。如果您正苦於以下問題:Python flask_cors.CORS屬性的具體用法?Python flask_cors.CORS怎麽用?Python flask_cors.CORS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在flask_cors的用法示例。


在下文中一共展示了flask_cors.CORS屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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)') 
開發者ID:IBM,項目名稱:MAX-Framework,代碼行數:23,代碼來源:app.py

示例2: init_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:hackathons-ftw,項目名稱:dribdat,代碼行數:22,代碼來源:app.py

示例3: create_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:tongyifan,項目名稱:Reseed-backend,代碼行數:24,代碼來源:__init__.py

示例4: initialize_api

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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": "*"}}) 
開發者ID:criteo,項目名稱:biggraphite,代碼行數:19,代碼來源:app.py

示例5: main

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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) 
開發者ID:vivithemage,項目名稱:mrisa,代碼行數:23,代碼來源:server.py

示例6: _config_cors

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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! 
開發者ID:ActivityWatch,項目名稱:aw-server,代碼行數:19,代碼來源:server.py

示例7: main

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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); 
開發者ID:lucivpav,項目名稱:cwg,代碼行數:23,代碼來源:server.py

示例8: create_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:lttkgp,項目名稱:C-3PO,代碼行數:12,代碼來源:manage.py

示例9: create_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:spotify,項目名稱:comet-core,代碼行數:31,代碼來源:api.py

示例10: check_origin

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:Cloud-CV,項目名稱:origami-lib,代碼行數:9,代碼來源:origami.py

示例11: __init__

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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) 
開發者ID:Cloud-CV,項目名稱:origami-lib,代碼行數:17,代碼來源:origami.py

示例12: build_flask_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:mozilla,項目名稱:code-coverage,代碼行數:40,代碼來源:build.py

示例13: get_flask_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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 
開發者ID:Erotemic,項目名稱:ibeis,代碼行數:50,代碼來源:controller_inject.py

示例14: create_app

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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) 
開發者ID:fastlane-queue,項目名稱:fastlane,代碼行數:50,代碼來源:app.py

示例15: main

# 需要導入模塊: import flask_cors [as 別名]
# 或者: from flask_cors import CORS [as 別名]
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)) 
開發者ID:jeffknupp,項目名稱:sandman2,代碼行數:62,代碼來源:__main__.py


注:本文中的flask_cors.CORS屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。