def create_app(config='config.ProductionDevelopmentConfig'): app = Flask(__name__) app.config.from_object(config) db.init_app(app) mixer.init_app(app) app.before_request(setup_authomatic(app)) app.before_request(load_user) app.add_url_rule('/', 'index', index) app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(issues_bp, url_prefix='/issues') app.register_blueprint(comments_bp, url_prefix='/comments') app.register_blueprint(organizations_bp, url_prefix='/organizations') admin = Admin(app) # add admin views. admin.add_view(AdminView(User, db.session)) admin.add_view(AdminView(Issue, db.session)) admin.add_view(AdminView(Comment, db.session)) admin.add_view(AdminView(Organization, db.session)) admin.add_view(AdminView(Vote, db.session)) return app
def create_app(): config_name = os.getenv('FLASK_CONFIG') or 'default' app = Flask(__name__) #: app配置环境处理 app.config.from_object(config[config_name]) config[config_name].init_app(app) #: 数据库处理 db.init_app(app) #: 加载所有restful resource api = Api(app) add_resources(api) #: 统一加载before_request for func in before_request_func: app.before_request(func) #: 统一加载after_request for func in after_request_func: app.after_request(func) #: 跨域访问, 指定允许的请求地址 直接指定参数,也可以指定单独path的跨域请求处理 #: https://flask-cors.readthedocs.io/en/latest/ CORS(app, origins=app.config['CORS_ORIGINS'], max_age=86400) return app
def create_app(conf): app = Flask(__name__, static_folder=conf.STATIC_DIR) app.config.from_object(conf) app.logger.addHandler(conf.X_LOG_HANDLER) app.logger.setLevel(conf.X_LOG_LEVEL) # Create all blueprints and modules (execute all models, views and admins). ns = create_modules() app.add_url_rule('/', 'index', ns['index']) app.register_blueprint(ns['places_app'], url_prefix="/places") app.register_blueprint(ns['tours_app'], url_prefix="/tours") app.register_blueprint(ns['auth_app'], url_prefix="/auth") app.before_request(ns['before_app_req']) # Create extensions. bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) mail.init_app(app) admin_files_managing() create_admin_menu() admin.init_app(app) app.logger.debug("Main app is created using config: {}".format(conf)) return app
def create_app(server): '''Create Flask application and attach TAXII server instance ``server`` to it. :param `opentaxii.server.TAXIIServer` server: TAXII server instance :return: Flask app ''' app = Flask(__name__) app.taxii_server = server server.init_app(app) app.add_url_rule("/<path:relative_path>", "opentaxii_services_view", _server_wrapper(server), methods=['POST', 'OPTIONS']) app.register_blueprint(management, url_prefix='/management') app.register_error_handler(500, handle_internal_error) app.register_error_handler(StatusMessageException, handle_status_exception) app.before_request(functools.partial(create_context_before_request, server)) return app
def setup_app(warnings=None): if warnings is None: warnings = [] app = Flask(__name__) cfy_config = config.instance() app.logger_name = 'manager-rest' # setting up the app logger with a rotating file handler, in addition to # the built-in flask logger which can be helpful in debug mode. create_logger(logger_name=app.logger.name, log_level=cfy_config.rest_service_log_level, log_file=cfy_config.rest_service_log_path, log_file_size_MB=cfy_config.rest_service_log_file_size_MB, log_files_backup_count=cfy_config. rest_service_log_files_backup_count) # log all warnings passed to function for w in warnings: app.logger.warning(w) # secure the app according to manager configuration if cfy_config.security_enabled: app.logger.info('initializing rest-service security') init_secured_app(app) app.before_request(log_request) app.after_request(log_response) # saving flask's original error handlers flask_handle_exception = app.handle_exception flask_handle_user_exception = app.handle_user_exception api = Api(app) # saving flask-restful's error handlers flask_restful_handle_exception = app.handle_exception flask_restful_handle_user_exception = app.handle_user_exception # setting it so that <500 codes use flask-restful's error handlers, # while 500+ codes use original flask's error handlers (for which we # register an error handler on somewhere else in this module) def handle_exception(flask_method, flask_restful_method, e): code = getattr(e, 'code', 500) if code >= 500: return flask_method(e) else: return flask_restful_method(e) app.handle_exception = functools.partial( handle_exception, flask_handle_exception, flask_restful_handle_exception) app.handle_user_exception = functools.partial( handle_exception, flask_handle_user_exception, flask_restful_handle_user_exception) endpoint_mapper.setup_resources(api) return app
def create_app(settings_object="jobserv.settings"): app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.config.from_object(settings_object) ProjectConverter.settings = settings_object app.url_map.converters["project"] = ProjectConverter from jobserv.models import db db.init_app(app) Migrate(app, db) import jobserv.api jobserv.api.register_blueprints(app) from jobserv.storage import Storage if Storage.blueprint: app.register_blueprint(Storage.blueprint) app.json_encoder = ISO8601_JSONEncoder app.before_request(_user_has_permission) return app
def create_app(config_string, validate_tokens=True): app = Flask(__name__) cfg = configuration.config.get(config_string) app.config.from_object(cfg) db.init_app(app) #: launch all views in the application by launching the api launcher (lol) #: version three api imported in create app to prevent circular dependencies #: when redis :object `rdb` is imported from any where in the application #: this is because the api accesses and registers the blueprint views which reference #: controllers which in turn reference the rdb. Life is bliss isn't it? from modules._api.rest import version_three version_three.launch_all_api(app) #: restrict post requests to json only app.before_request(version_three.allow_only_json) if validate_tokens: app.before_request(version_three.validate_token) @app.route("/", methods=["GET"]) def home(): return Response(apidoc(), mimetype='text/html') @app.route('/.well-known/acme-challenge/<token_value>') def letsencrpyt(token_value): with open( os.path.join( os.path.dirname('..'), '.well-known/acme-challenge/{}'.format(token_value))) as f: answer = f.readline().strip() print answer return answer return app
def init_app(app: Flask) -> None: """Init the cache for the given app. """ app.before_request(_set_g_vars) # Clear vars after request so that the values in ``cg_function_cache`` can # be garbage collected. app.after_request(_clear_g_vars)
def create_app(debug=False): app = Flask(__name__) app.debug = debug app.secret_key = 'this is a secret' app.json_encoder = Jsonifier app.file_root = os.path.abspath(os.path.dirname(__file__)) app.before_request(before_request) app.after_request(after_request) app.context_processor(context_processor) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db.init_app(app) with app.app_context(): init_all() app.register_blueprint(admin_app, url_prefix='/admin') app.register_blueprint(campaign_app, url_prefix='/') app.register_blueprint(character_app, url_prefix='/character') app.register_blueprint(dm_app, url_prefix='/dm') app.register_blueprint(chat_app, url_prefix='/chat') app.register_blueprint(items_app, url_prefix='/item-type') app.register_blueprint(knowledge_app, url_prefix='/knowledge') return app
def create_app(): """Set flask APP config, and start the data manager.""" gunicorn_logger = setup_logger("gunicorn", "error") gunicorn_logger.info("create_app starts.") static_url_path = settings.URL_PATH_PREFIX + "/static" static_folder_path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'ui', 'dist', 'static')) app = Flask(__name__, static_url_path=static_url_path, static_folder=static_folder_path) app.config['JSON_SORT_KEYS'] = False if settings.ENABLE_CORS: CORS(app, supports_credentials=True) app.before_request(before_request) app.register_error_handler(HTTPException, error_handler.handle_http_exception_error) app.register_error_handler(MindInsightException, error_handler.handle_mindinsight_error) app.register_error_handler(Exception, error_handler.handle_unknown_error) app.response_class = CustomResponse _init_app_module(app) gunicorn_logger.info("create_app ends.") return app
class BaseOpenstackDummy(Resource): """ This class is the base class for all openstack entrypoints of son-emu. """ def __init__(self, listenip, port): self.ip = listenip self.port = port self.compute = None self.manage = None self.playbook_file = '/tmp/son-emu-requests.log' with open(self.playbook_file, 'w'): pass # setup Flask self.app = Flask(__name__) self.api = Api(self.app) def _start_flask(self): LOG.info("Starting %s endpoint @ http://%s:%d" % (__name__, self.ip, self.port)) if self.app is not None: self.app.before_request(self.dump_playbook) self.app.run(self.ip, self.port, debug=True, use_reloader=False) def dump_playbook(self): with self.manage.lock: with open(self.playbook_file, 'a') as logfile: if len(request.data) > 0: data = "# %s API\n" % str( self.__class__).split('.')[-1].rstrip('\'>') data += "curl -X {type} -H \"Content-type: application/json\" -d '{data}' {url}".format( type=request.method, data=request.data, url=request.url) logfile.write(data + "\n")
def _build_pipeline_app(): """Configure and return the app with non-resource pipeline-triggering endpoints.""" offline_app = Flask(__name__) offline_app.add_url_rule( PREFIX + 'BiobankSamplesImport', endpoint='biobankSamplesImport', view_func=import_biobank_samples, methods=['GET']) offline_app.add_url_rule( PREFIX + 'MetricsRecalculate', endpoint='metrics_recalc', view_func=recalculate_metrics, methods=['GET']) offline_app.add_url_rule( PREFIX + 'PublicMetricsRecalculate', endpoint='public_metrics_recalc', view_func=recalculate_public_metrics, methods=['GET']) offline_app.add_url_rule( PREFIX + 'ExportTables', endpoint='ExportTables', view_func=export_tables, methods=['POST']) offline_app.after_request(app_util.add_headers) offline_app.before_request(app_util.request_logging) offline_app.register_error_handler(DBAPIError, app_util.handle_database_disconnect) return offline_app
def create_app(config_name = 'default'): app = Flask(__name__, static_folder='static', static_url_path='') app.config.from_object(config[config_name]) app.debug = True config[config_name].init_app(app) db.init_app(app) # attach routes and custom error pages here from hacer.api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') @app.route('/') def index(): return app.send_static_file('index.html') # start discovery server with app.app_context(): from discovery import run_discovery_server app.discovery_thread = Thread(target=run_discovery_server, kwargs={ "Session": scoped_session(sessionmaker(bind=db.engine)) }) app.discovery_thread.daemon = True app.discovery_thread.start() app.before_request(create_before_request(app)) return app
def create_app(configuration=None): from snow import config from snow import query from snow import model from snow import export from snow import features from snow.tracking import tracking from snow.ptscreen import pscr app = Flask(__name__) app.config.from_object(configuration or config.Configuration) _setup_logging(app.config[C.LOGGING_CONFIG_FILE]) app.before_request(log_request_info) pscr.init_app(app) model.cdm.init_app(app) tracking.init_app(app) app.add_url_rule('/', view_func=lambda: app.send_static_file('index.html')) app.add_url_rule('/stats', 'stats', query.patient_stats) app.add_url_rule('/download', 'download', export.download_patients) app.add_url_rule('/export', 'export', export.export_patients, methods=['POST']) app.add_url_rule('/ymca_stats', 'ymca_stats', query.ymca_stats) app.add_url_rule('/model', 'model', model.get_criteria_data_model) app.add_url_rule('/features', 'features', features.get_feature_flags) return app
class BaseOpenstackDummy(Resource): """ This class is the base class for all openstack entrypoints of son-emu. """ def __init__(self, listenip, port): self.ip = listenip self.port = port self.compute = None self.manage = None self.playbook_file = '/tmp/son-emu-requests.log' with open(self.playbook_file, 'w'): pass # setup Flask self.app = Flask(__name__) self.api = Api(self.app) def _start_flask(self): LOG.info("Starting %s endpoint @ http://%s:%d" % (__name__, self.ip, self.port)) if self.app is not None: self.app.before_request(self.dump_playbook) self.app.run(self.ip, self.port, debug=True, use_reloader=False) def dump_playbook(self): with self.manage.lock: with open(self.playbook_file, 'a') as logfile: if len(request.data) > 0: data = "# %s API\n" % str(self.__class__).split('.')[-1].rstrip('\'>') data += "curl -X {type} -H \"Content-type: application/json\" -d '{data}' {url}".format(type=request.method, data=request.data, url=request.url) logfile.write(data + "\n")
def init_app(app: Flask) -> None: @app.context_processor def _inject_logged_in(): # 是否已登录 logged_in = session.get('logged_in', False) return dict(logged_in=logged_in) app.add_url_rule('/', 'home', home) app.add_url_rule('/favicon.ico', 'favicon', favicon) app.add_url_rule('/add', 'add', add, methods=['GET', 'POST']) app.add_url_rule('/delete/<int:id>', 'delete', delete) app.add_url_rule('/update/<int:id>', 'update', update, methods=['GET', 'POST']) app.add_url_rule('/detail/<int:id>', 'detail', detail) app.add_url_rule('/login', 'login', login, methods=['GET', 'POST']) app.add_url_rule('/logout', 'logout', logout) app.add_url_rule('/change_key', 'change_key', change_key, methods=['GET', 'POST']) app.add_url_rule('/about', 'about', about) app.before_request(before_request) app.after_request(after_request) app.add_template_filter(_jinja2_filter_datetime, 'strftime') app.register_error_handler(404, not_found)
def create_app(): app = Flask(__name__) # only need this for localhost if app.debug: cors = CORS( app, resources={r"/*": { "origins": "*" }}, methods=['GET', 'HEAD', 'POST', 'OPTIONS'], supports_credentials=True, ) app.config["SQLALCHEMY_DATABASE_URI"] = environ["SQLALCHEMY_DATABASE_URI"] # app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) app.before_request(load_principal_from_serverless) app.before_request(instanciate_datasources) @app.route("/") def index(): return "Server is running<br><a href='/graphql'>Server</a>" app.add_url_rule("/graphql", view_func=graphql_view(app.debug)) return app
def create_app(config_name='Config'): app = Flask(__name__) config_name = os.getenv('APP_SETTINGS', config_name) app.config.from_object(f'config.{config_name}') # Set the secret key to some random bytes. Keep this really secret! app.secret_key = app.config.get('OPS_UI_SECRET') if app.config['IN_GCP'] == 'true': app.wsgi_app = ProxyFix(app.wsgi_app) logger_initial_config(app.config) logger = wrap_logger(logging.getLogger(__name__)) logger.info('Starting Census Response Operations UI', app_log_level=app.config['LOG_LEVEL'], environment=app.config['ENVIRONMENT']) assets = Environment(app) assets.url = app.static_url_path scss_min = Bundle('css/*', 'css/fonts/*', 'css/components/*', filters=['cssmin'], output='minimised/all.min.css') assets.register('scss_all', scss_min) js_min = Bundle('js/*', filters='jsmin', output='minimised/all.min.js') assets.register('js_all', js_min) app.before_request( partial(log_iap_audit, iap_audience=app.config['IAP_AUDIENCE'])) setup_blueprints(app) return app
def create_app(config_name=None): """创建和注册 app 的函数 注册日志处理器、扩展、蓝本、自定义 shell 命令、错误处理函数、shell 上下文处理函数和模板上下文注册函数 Args: config_name:配置的名称,默认为 None Returns: 返回注册完成后的 app """ if config_name is None: config_name = os.getenv('FLASK_CONFIG') app = Flask('bluelog') app.config.from_object(config[config_name]) app.before_request(jwt_authentication) # 添加请求钩子 register_logger(app) # 注册日志处理器 register_extensions(app) # 注册扩展(扩展初始化) register_blueprints(app) # 注册蓝本 register_commands(app) # 注册自定义 shell 命令 register_errors(app) # 注册错误处理函数 register_shell_context(app) # 注册 shell 上下文处理函数 register_template_context(app) # 注册模板上下文处理函数 return app
def init_app() -> Flask: """ アプリ起動時、リロード時にしか呼ばれない """ Logger() app = Flask(__name__) # flask環境変数指定 app.secret_key = config().SECRET_KEY # Bliueprint app.register_blueprint(signup.bp) app.register_blueprint(user.bp) app.before_request(before_action) app.after_request(after_action) FlaskInjector(app=app, modules=[UsecaseDIModule(), RepositoryDIModule()]) Swagger(app, template=template) logger.debug("app initialized") logger.debug(f"URL Map: {app.url_map}") logger.debug(f"app.config: {app.config}") logger.debug(f"config: {config().dict()}") return app
def create_app(): app = Flask(__name__) # Append CORS headers to each request. app.after_request(cors_headers) # Register views. app.register_blueprint(main) app.register_blueprint(debug) app.register_blueprint(images) app.register_blueprint(static) app.register_blueprint(status) # Use a dummy data generator while Yahoo BOSS access is being sorted out. app.register_blueprint(dummy) # Log using the mozlog format to stdout. handler = StreamHandler(stream=stdout) handler.setFormatter(MozLogFormatter(logger_name='universalSearch')) handler.setLevel(INFO) app.logger_name = 'request.summary' app.logger.addHandler(handler) app.logger.setLevel(INFO) # Use logging middleware. if not conf.TESTING: app.before_request(request_timer) app.after_request(request_summary) app.config.update( CELERY_BROKER_URL=conf.CELERY_BROKER_URL, DEBUG=conf.DEBUG, SERVER_NAME=conf.SERVER_NAME ) return app
def _create_app(config): app = Flask(__name__) api = ExceptionHandlingApi(app) api_doc_route = '/api-docs' api_metrics_route = '/metrics' health_route = '/health' info_route = '/info' api.add_resource(DataSetSearchResource, config.app_base_path) api.add_resource(ApiDoc, api_doc_route) api.add_resource(MetadataEntryResource, config.app_base_path + '/<entry_id>') api.add_resource(TableResource, config.app_base_path + '/<entry_id>/table') api.add_resource(DataSetCountResource, config.app_base_path + '/count') api.add_resource(ElasticSearchAdminResource, config.app_base_path + '/admin/elastic') app.route(api_metrics_route)(_get_metrics) app.route(info_route, endpoint=info_route)( lambda: jsonify(name=version.NAME, app_version=version.VERSION)) app.route(health_route, endpoint=health_route)(lambda: jsonify(status="UP")) security = Security(auth_exceptions=[ api_doc_route, api_metrics_route, health_route, info_route ]) app.before_request(security.authenticate) return app
def create_app(env_name): """ Create app """ # app initiliazation app = Flask(__name__) app.config.from_object(app_config[env_name]) attach_logger(app) app.logger.setLevel(logging.DEBUG) # Register endpoint routes here: hello.register(app) auth.register(app) users.register(app) oeci_login.register(app) search.register(app) app.before_request(before) app.teardown_request(teardown) app.logger.debug("Flask app created!") return app
def create_app(config=None): """ initialize application """ global app, db app = Flask(__name__) print("create app(%s) id:%s" % (__name__, id(app))) assert config # load config path x = app.config.from_pyfile(config, silent=False) # --------- DB ----------------- db = SQLAlchemy(app) print("create db id:%s via %r" % (id(db), SQLAlchemy)) from inc import casbin_adapter install_models(app.config['INSTALLED_APPS']) assert db db.create_all() casbin_adapter.adapter = casbin_adapter.Adapter(db) casbin_adapter.rbac = casbin.Enforcer(app.config["CASBIN_CONFIG_PATH"], casbin_adapter.adapter, False) install() if app.config.get('DEBUG'): app.before_request(befor_request_callbacks) app.after_request(after_request_callbacks) return app
def create_app(): # 创建flask app app = Flask(__name__) # 加载配置 from .config import Config from .extensions import db, markdown from .lang import text from .helper import siteconfig, categories, menus from . import lang app.config.from_object(Config) db.init_app(app) lang.setup(app.config.get('LANGUAGE', 'en_GB')) app.jinja_env.globals.update(__=text) app.jinja_env.globals.update(site=siteconfig, site_categories=categories, menus=menus, enumerate=enumerate) app.jinja_env.filters['markdown'] = markdown.convert # 注册蓝图 from .controller import admin_bp, site_bp from .views import home app.register_blueprint(admin_bp) app.register_blueprint(site_bp) app.register_blueprint(home) # 注册钩子方法 app.before_request(init_user) return app
def create_app(settings_override=None): """Returns a `Flask` application instance configured. """ app = Flask(__name__, instance_relative_config=True) app.config.from_object('fki_challenge.settings') app.config.from_pyfile('application.cfg', silent=True) app.config.from_object(settings_override) api = Api(app, prefix='/api', catch_all_404s=True) # ensure tables models.database.init(app.config['FKI_DATABASE_FILE']) models.database.connect() models.database.create_tables([models.Attribute, models.Person, models.PersonAttribute], safe=True) # register db request hooks app.before_request(_db_connect) app.teardown_request(_db_close) # wire resources api.add_resource(resources.Attribute, '/attributes/<int:attribute_id>') api.add_resource(resources.AttributeList, '/attributes/') api.add_resource(resources.Person, '/persons/<int:person_id>') api.add_resource(resources.PersonList, '/persons/') api.add_resource(resources.MatchList, '/matches/', resource_class_kwargs={'error_rate': app.config['FKI_ERROR_RATE']}) return app
def register_before_request_handlers(application: Flask) -> None: """ Register handlers that will be executed before each request. :param application: The application instance for which the handlers will be registered. """ application.before_request(_extend_global_variable)
def setup_app(warnings=None): if warnings is None: warnings = [] app = Flask(__name__) cfy_config = config.instance() _detect_debug_environment() app.logger_name = 'manager-rest' # setting up the app logger with a rotating file handler, in addition to # the built-in flask logger which can be helpful in debug mode. create_logger( logger_name=app.logger.name, log_level=cfy_config.rest_service_log_level, log_file=cfy_config.rest_service_log_path, log_file_size_MB=cfy_config.rest_service_log_file_size_MB, log_files_backup_count=cfy_config.rest_service_log_files_backup_count) # log all warnings passed to function for w in warnings: app.logger.warning(w) # secure the app according to manager configuration if cfy_config.security_enabled: app.logger.info('initializing rest-service security') init_secured_app(app) app.before_request(log_request) app.after_request(log_response) # saving flask's original error handlers flask_handle_exception = app.handle_exception flask_handle_user_exception = app.handle_user_exception api = Api(app) # saving flask-restful's error handlers flask_restful_handle_exception = app.handle_exception flask_restful_handle_user_exception = app.handle_user_exception # setting it so that <500 codes use flask-restful's error handlers, # while 500+ codes use original flask's error handlers (for which we # register an error handler on somewhere else in this module) def handle_exception(flask_method, flask_restful_method, e): code = getattr(e, 'code', 500) if code >= 500: return flask_method(e) else: return flask_restful_method(e) app.handle_exception = functools.partial(handle_exception, flask_handle_exception, flask_restful_handle_exception) app.handle_user_exception = functools.partial( handle_exception, flask_handle_user_exception, flask_restful_handle_user_exception) endpoint_mapper.setup_resources(api) return app
def customize_flask(app: Flask, update_global_func, official_website, debug=False): # Make sure everything works when behind Apache proxy app.wsgi_app = ProxyFix(app.wsgi_app) # Set debug level to whatever the settings say app.debug = debug # Make sure we do not use stale data app.before_request(update_global_func) # Redirect so we remove query strings (or else, you could circumvent the # cache by using arbitrary get parameters) app.before_request(ignore_get) # Ensure the favicon is available at /favicon.ico (we have no other way of # specifying a favicon when serving an XML document) app.add_url_rule("/favicon.ico", "redirect_to_favicon", redirect_to_favicon) # Ensure / redirects to official website def do_redirect_to_website(): return redirect_to_website(official_website) app.add_url_rule( "/", "redirect_to_website", do_redirect_to_website, )
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(SECRET_KEY='AplikacjaDlaStasia', DATABASE=os.path.join(app.root_path, '..', 'db.sqlite'), SITE_NAME='Zeton') if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) app.teardown_appcontext(db.close_db) app.add_template_filter(jinja2_ban_datetime_filter, 'ban_time') app.register_blueprint(auth.bp) app.register_blueprint(views.bp) app.register_blueprint(api.bp) app.register_blueprint(errors.bp) app.before_request(users.load_logged_in_user_data) return app
def create_app(): app = Flask(__name__) # Append CORS headers to each request. app.after_request(cors_headers) # Register views. app.register_blueprint(main) app.register_blueprint(static) app.register_blueprint(status) # Use a dummy data generator while Yahoo BOSS access is being sorted out. app.register_blueprint(dummy) # Log using the mozlog format to stdout. handler = StreamHandler(stream=stdout) handler.setFormatter(MozLogFormatter(logger_name='universalSearch')) handler.setLevel(INFO) app.logger_name = 'request.summary' app.logger.addHandler(handler) app.logger.setLevel(INFO) # Use logging middleware. if not conf.TESTING: app.before_request(request_timer) app.after_request(request_summary) app.config.update( CELERY_BROKER_URL=conf.CELERY_BROKER_URL, DEBUG=conf.DEBUG ) return app
def create_app(config_file): app = Flask("muffin") app.config.from_pyfile(config_file) if app.debug: app.logger.setLevel(logging.DEBUG) # set up wanted middleware if app.config.get('PROFILE', False): # pragma: no cover # no-cover we don't want to verify profile configs app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[10]) def before_request(): g.muffin_start_request = time.clock() def after_request(response): end = time.clock() response.headers['X-ElapsedTime'] = end - g.muffin_start_request return response app.before_request(before_request) app.after_request(after_request) # init backend backend.init_app(app) # install error handlers app.register_blueprint(muffin_error.muffin_error) # register api blueprints register_api(app, url_prefix="/api/v2") return app
def create_app(config_file): app = Flask(__name__) # configuration settings are loaded from the `config.py` module # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to app.config.from_pyfile(config_file) app.config.from_envvar('XSNIPPET_WEBUI_SETTINGS', silent=True) # set jinja2 global vars to be used in all templates app.jinja_env.globals.update( { "title": app.config["TITLE"], "abs_url_for": abs_url_for, "lang_by_short_name": lang_by_short_name } ) # set assets env assets.Environment(app) app.register_blueprint(webui) # register all needed hooks app.before_request(create_http_object) # create cache connection (it's thread-safe) app.cache = create_cache_connection(app, key_prefix="webui_") return app
def init_app_without_routes(disable_csrf=False): app = Flask(__name__) app.secret_key = config.get_config()['sessions_secret'] app.config['SQLALCHEMY_DATABASE_URI'] = config.get_config( )['postgres']['url'] if config.get_config()['postgres'].get('commercial_url'): app.config['SQLALCHEMY_BINDS'] = { 'commercial': config.get_config()['postgres']['commercial_url'] } app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False global db class SQLAlchemy(_BaseSQLAlchemy): def apply_pool_defaults(self, app, options): super(SQLAlchemy, self).apply_pool_defaults(app, options) options["pool_pre_ping"] = True db = SQLAlchemy(app) from modules.base import authentication if os.getenv('ENVIRONMENT') == 'test_env': app.before_request(authentication.login_test_user) @app.errorhandler(403) def handle_403(error): return jsonify({ 'error_type': 'error_bar', 'error': error.description or '' }), 403 login_manager = LoginManager() login_manager.init_app(app) global csrf_protect if not disable_csrf: csrf_protect = CSRFProtect() csrf_protect.init_app(app) @login_manager.user_loader def load_user(user_id): from modules.users.helpers import get_user_by_id sentry_sdk.set_user({'id': user_id}) return get_user_by_id(user_id) app.before_request(authentication.validate_user_authentication) @app.route('/_/health_check') def health_check(): return 'OK' return app
def create_app(config_name='testing'): """Create an application.""" app = Flask(__name__) app.config.from_object(config[os.environ.get('FLASK_ENV', config_name)]) # User from .user import user as user_blueprint app.register_blueprint(user_blueprint) # Add the before request handler app.before_request(create_before_request(app)) # API CORS(app) api.init_app(app) # Database db.init_app(app) # Marshmallow ma.init_app(app) # This does the binding app.app_context().push() # Initialize DB db.create_all() return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping({ "SECRET_KEY": "dev", "DATABASE": { "user": "******", "password": "******", "database": "burger_builder", "host": "localhost", "port": 3306 } }) if test_config: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass init_app(app) app.before_request(auth_validator) app.register_blueprint(sign_up.bp) app.register_blueprint(auth.bp) app.register_blueprint(orders.bp) return app
def register_extensions(app: Flask): """组件初始化""" # SQLAlchemy组件初始化 from app import db db.init_app(app) # redis组件初始化 global redis_client redis_client = StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], decode_responses=True) # 添加转换器 from utils.converters import register_converters register_converters(app) # 数据迁移组件初始化 Migrate(app, db) from models import user # 添加请求钩子 from utils.middlewares import get_userinfo app.before_request(get_userinfo) # CORS(app, supports_credentials=True) # 导入模型类 from models import user, article
def includeme(config): app = Flask('annotator') # Create the annotator-store app app.register_blueprint(store.store) # and register the store api. # Set up the models settings = config.get_settings() if 'es.host' in settings: app.config['ELASTICSEARCH_HOST'] = settings['es.host'] if 'es.index' in settings: app.config['ELASTICSEARCH_INDEX'] = settings['es.index'] es.init_app(app) with app.test_request_context(): Annotation.create_all() Document.create_all() # Configure authentication and authorization app.config['AUTHZ_ON'] = True app.before_request(before_request) # Configure the API views -- version 1 is just an annotator.store proxy api_v1 = wsgiapp2(app) config.add_view(api_v1, route_name='api') if not config.registry.queryUtility(interfaces.IStoreClass): config.registry.registerUtility(Store, interfaces.IStoreClass)
def create_app(): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_object(Configuration) app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(days=4000) db.init_app(app.config.get("LOCAL_DYNAMODB"), prefix=app.config["TABLE_PREFIX"]) CORS(app, supports_credentials=True) mastodon_bp = make_mastodon_blueprint( app.config["SERVICE_NAME"], scope="read", instance_credentials_backend=OAuthDynamoDbMemoryBackend(), ) app.register_blueprint(mastodon_bp, url_prefix="/login") app.before_request(populate_actor_info) app.register_blueprint(site, url_prefix="/") app.register_blueprint(groupAPI, url_prefix="/api") app.register_blueprint(groupViews, url_prefix="/group") return app
def init_app(cls, app: Flask) -> None: """初始化flask应用对象""" app.before_request(before_app_request) app.teardown_request(teardown_app_request) app.json_encoder = CustomJSONEncoder sub, url = cls.BP_SUB_DOMAIN, cls.BP_URL_PREFIX app.register_blueprint(bp_admin_api, subdomain=sub.get('admin'), url_prefix=url.get('admin_api')) app.register_blueprint(bp_admin_ext, subdomain=sub.get('admin'), url_prefix=url.get('admin_ext')) # 日志 formatter = logging.Formatter( '[%(asctime)s] %(pathname)s:%(lineno)d [%(levelname)s] %(message)s' ) debug_log = RotatingFileHandler('debug.log', maxBytes=1024 * 1024 * 100, backupCount=10, encoding='utf-8') debug_log.setLevel(logging.DEBUG) debug_log.setFormatter(formatter) error_log = RotatingFileHandler('error.log', maxBytes=1024 * 1024 * 100, backupCount=10, encoding='utf-8') error_log.setLevel(logging.ERROR) error_log.setFormatter(formatter) app.logger.setLevel(logging.DEBUG) app.logger.addHandler(debug_log) app.logger.addHandler(error_log)
def create_app(): app = Flask(__name__) api = Api(app) app.config.from_object('config.default') app.config.from_envvar('APP_SETTINGS', silent=False) app.add_url_rule('/api/login', 'login', _get_token) from models.base import db db.init_app(app) from controllers.index import Index from controllers.user import UsersList, UserSingle from controllers.tasks import TaskSingle, Tasks, AssignTask from controllers.comments import Comments from controllers.reports import UserComments, TaskStats app.before_request(db_connect.before_request) app.after_request(db_connect.after_request) app.add_url_rule('/api/tasks/<int:task_id>/comments', view_func=Comments.as_view(COMMENTS)) api.add_resource(Index, '/api/index') api.add_resource(UsersList, '/api/users') api.add_resource(UserSingle, '/api/users/<int:user_id>') api.add_resource(Tasks, '/api/tasks') api.add_resource(TaskSingle, '/api/tasks/<int:task_id>') api.add_resource(AssignTask, '/api/assign_task') api.add_resource(UserComments, '/api/reports/user_comments') api.add_resource(TaskStats, '/api/reports/task_stats') return app
class ChainApi(Resource): """ The chain API is a component that is not used in OpenStack. It is a custom built REST API that can be used to create network chains and loadbalancers. """ def __init__(self, inc_ip, inc_port, manage): # setup Flask self.app = Flask(__name__) self.api = Api(self.app) self.ip = inc_ip self.port = inc_port self.manage = manage self.playbook_file = '/tmp/son-emu-requests.log' self.api.add_resource(ChainVersionsList, "/", resource_class_kwargs={'api': self}) self.api.add_resource(ChainList, "/v1/chain/list", resource_class_kwargs={'api': self}) self.api.add_resource(ChainVnfInterfaces, "/v1/chain/<src_vnf>/<src_intfs>/<dst_vnf>/<dst_intfs>", resource_class_kwargs={'api': self}) self.api.add_resource(ChainVnfDcStackInterfaces, "/v1/chain/<src_dc>/<src_stack>/<src_vnf>/<src_intfs>/<dst_dc>/<dst_stack>/<dst_vnf>/<dst_intfs>", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHostList, "/v1/lb/list", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHost, "/v1/lb/<vnf_src_name>/<vnf_src_interface>", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHostDcStack, "/v1/lb/<src_dc>/<src_stack>/<vnf_src_name>/<vnf_src_interface>", resource_class_kwargs={'api': self}) self.api.add_resource(QueryTopology, "/v1/topo", resource_class_kwargs={'api': self}) self.api.add_resource(Shutdown, "/shutdown") @self.app.after_request def add_access_control_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response def _start_flask(self): logging.info("Starting %s endpoint @ http://%s:%d" % ("ChainDummyApi", self.ip, self.port)) if self.app is not None: self.app.before_request(self.dump_playbook) self.app.run(self.ip, self.port, debug=True, use_reloader=False) def dump_playbook(self): with self.manage.lock: with open(self.playbook_file, 'a') as logfile: data = "# CHAIN API\n" if len(request.data) > 0: data += "curl -X {type} -H \"Content-type: application/json\" -d '{data}' {url}".format(type=request.method, data=request.data, url=request.url) else: data += "curl -X {type} -H \"Content-type: application/json\" {url}".format( type=request.method, url=request.url) logfile.write(data + "\n")
def test_noninstrospectable_hooks_dont_crash_everything(): app = Flask(__name__) def do_nothing(): pass app.before_request(partial(do_nothing)) # It'd crash here FlaskInjector(app=app)
def create_app(config): """ This method is a factory for our Flask app which configures all the necessary behavior and register all the blueprints. All our views should belong to a blueprint and the blueprints mounted on the main App. To run our application you need only to instantiate a app using this function, given a config object, and call its run method. example: datalog_app = create_app(my_config_obj) datalog_app.run() """ app = Flask('datalog') app.config.from_object(config) db = config.get_db() def call_end_request(response): """ flush pending mongodb requests and return the connection to the poll """ db.connection.end_request() return response def add_db_to_request(): """ makes possible to access the db directly from any view (possible, but **not encouraged**, avoid doing this) """ g.db = db def permanet_sessions(): """ makes the session persistent for PERMANENT_SESSION_LIFETIME """ session.permanent = True app.before_request(add_db_to_request) app.before_request(permanet_sessions) app.after_request(call_end_request) # register blueprints app.register_blueprint(app_views) connect_models(config) return app
def create_app(config={}): app = Flask(__name__) app.config.from_object('App.config_dev') app.config.update(config) db.init_app(app) register_all_views(app) login_manager.init_app(app) app.before_request(before_request) return app
def setup_app(): app = Flask(__name__) # setting up the app logger with a rotating file handler, in addition to # the built-in flask logger which can be helpful in debug mode. additional_log_handlers = [ RotatingFileHandler( config.instance().rest_service_log_path, maxBytes=1024*1024*100, backupCount=20) ] app.logger_name = 'manager-rest' setup_logger(logger_name=app.logger.name, logger_level=logging.DEBUG, handlers=additional_log_handlers, remove_existing_handlers=False) app.before_request(log_request) app.after_request(log_response) # saving flask's original error handlers flask_handle_exception = app.handle_exception flask_handle_user_exception = app.handle_user_exception api = Api(app) # saving flask-restful's error handlers flask_restful_handle_exception = app.handle_exception flask_restful_handle_user_exception = app.handle_user_exception # setting it so that <500 codes use flask-restful's error handlers, # while 500+ codes use original flask's error handlers (for which we # register an error handler on somewhere else in this module) def handle_exception(flask_method, flask_restful_method, e): code = getattr(e, 'code', 500) if code >= 500: return flask_method(e) else: return flask_restful_method(e) app.handle_exception = functools.partial( handle_exception, flask_handle_exception, flask_restful_handle_exception) app.handle_user_exception = functools.partial( handle_exception, flask_handle_user_exception, flask_restful_handle_user_exception) resources.setup_resources(api) return app
def create_app(config=None): app = Flask(__name__) app.name = APP_NAME app.config.update(default_config) if config is not None: app.config.update(config) app.before_request(ensure_session) app.register_blueprint(api.blueprint) return app
def create_app(): app = Flask(__name__) app.config.from_object('doc_indexer.config') # Flask-SQLAlchemy db.init_app(app) app.before_request(db_start_session) app.teardown_request(db_commit_session) # Flask-Uploads configure_uploads(app, (document_uploads,)) register_blueprints(app) return app
def test_requestdebugging(self): custom_app = Flask(__name__) custom_app.before_request(log_request) @custom_app.route('/foo') def foo(): return '' with custom_app.test_request_context('/foo'): with custom_app.test_client() as client: with patch('flask.current_app.logger.debug') as mocked_debug: client.get('/foo') self.assertEqual(mocked_debug.call_count, 1)
def _create_app(config): app = Flask(__name__) api = ExceptionHandlingApi(app) api_doc_route = '/api-docs' api.add_resource(DataSetSearchResource, config.app_base_path) api.add_resource(ApiDoc, api_doc_route) api.add_resource(MetadataEntryResource, config.app_base_path + '/<entry_id>') api.add_resource(DataSetCountResource, config.app_base_path + '/count') api.add_resource(ElasticSearchAdminResource, config.app_base_path + '/admin/elastic') security = Security(auth_exceptions=[api_doc_route]) app.before_request(security.authenticate) return app
def create_app(config): """ Application Factories - http://flask.pocoo.org/docs/patterns/appfactories/ :param config: Path to config.py file. """ app = Flask(__name__) app.config.from_pyfile(config) db.init_app(app) api = Api(app) from application.json_encoder import AlchemyEncoder app.json_encoder = AlchemyEncoder # Register middlewares here from application.middlewares import require_login, apply_cors_headers app.before_request(require_login) app.after_request(apply_cors_headers) # Register blueprints here from application.views import bp as bp_auth app.register_blueprint(bp_auth) from application.views import UserList, UserResource, GroupList, SubjectList, SubjectSignupList, \ SubjectSignupResource, TermSignupAction, SettingList api.add_resource(UserList, '/api/users') api.add_resource(UserResource, '/api/users/<int:id>') api.add_resource(GroupList, '/api/groups') api.add_resource(SubjectList, '/api/subjects') api.add_resource(SubjectSignupList, '/api/subjects_signup') api.add_resource(SubjectSignupResource, '/api/subjects_signup/<int:subject_id>') api.add_resource(TermSignupAction, '/api/terms/signup') api.add_resource(SettingList, '/api/settings') # Admin panel from application.models import User, Group, Subject, Term, TermSignup, Setting from application.admin import UserAdminView, SubjectAdminView, TermAdminView, TermSignupAdminView, SettingAdminView admin = Admin(app) admin.add_view(UserAdminView(User, db.session)) admin.add_view(ModelView(Group, db.session)) admin.add_view(SubjectAdminView(Subject, db.session)) admin.add_view(TermAdminView(Term, db.session)) admin.add_view(TermSignupAdminView(TermSignup, db.session)) admin.add_view(SettingAdminView(Setting, db.session)) return app
def init_app(): app = Flask(__name__) app.config.from_object(config) app.before_request(get_current_user) app.before_request(db_session) blueprints = Blueprints(app) app = blueprints.register() login_manager.init_app(app) mail = Mail(app) Base = declarative_base() db = SQLAlchemy(app) class UserModify(db.Model, User): pass db_adapter = SQLAlchemyAdapter(db, UserModify) user_manager = UserManager(db_adapter, app) return app
def includeme(config): """Include the annotator-store API backend. Example INI file: [app:h] consumer_key: primary_consumer consumer_secret: 00000000-0000-0000-0000-000000000000 """ settings = config.get_settings() if not settings.has_key('h.consumer_key'): raise KeyError('h.consumer_key') if not settings.has_key('h.consumer_secret'): raise KeyError('h.consumer_secret') # Create the annotator-store app app = Flask(__name__) app.register_blueprint(store.store) # Set up the models es.init_app(app) with app.test_request_context(): try: Annotation.create_all() except: Annotation.update_settings() Annotation.create_all() # Configure authentication (ours) and authorization (store) authenticator = auth.Authenticator(consumer_fetcher) def before_request(): g.auth = authenticator g.authorize = authz.authorize app.before_request(before_request) # Configure the API views config.add_view(wsgiapp2(app), route_name='api') config.add_view(token, route_name='token', permission='authenticated') config.add_view(users, route_name='users', request_method='GET', permission='authenticated', renderer='json')
class RestProvider(APIProvider): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.app = Flask("iris-rest") # Make sure we have config if 'rest' not in self.daemon.config.providers: raise Exception("No config for RestProvider (need config.providers.rest)") self.config = self.daemon.config.providers['rest'] # Grab config vars self.host = self.config.get("host", "0.0.0.0") self.port = self.config.get("port", "8080") self.auth = self.config.get("auth") # Meta Registers self.app.register_error_handler(APIBase, self.handle_response) self.app.before_request(self.before_request) self.app.add_url_rule('/', 'index', self.route_index) # Controllers self.app.register_blueprint(ShardController(self).bp) self.app.register_blueprint(EntryController(self).bp) def before_request(self): if self.auth and request.headers.get("IRIS_AUTH") != self.auth: raise APIError("Invalid Credentials", 1000) def handle_response(self, obj): return jsonify(obj.data) def run(self): super().run() self.app.run(host=self.host, port=self.port) def route_index(self): raise APIResponse({ "stats": { "uptime": float("{0:.4f}".format(time.time() - self.daemon.start_time)), }, "version": __VERSION__ })
def create_app(): app = Flask(__name__) with open('/etc/ella/settings.yml') as f: app.config.update(**yaml.load(f)) ELLIPTICS_HOSTNAME = app.config.get('ELLIPTICS_HOSTNAME') if ELLIPTICS_HOSTNAME: app.node = init_elliptics(ELLIPTICS_HOSTNAME) else: app.before_request(before) app.add_url_rule('/', 'home', view_func=views.home, methods=['GET', 'POST']) app.add_url_rule('/routing', view_func=views.routing) app.add_url_rule('/stats', view_func=views.stats) app.add_url_rule('/find', view_func=views.find) app.add_url_rule('/download/<string:key>', view_func=views.download) return app
def test_enforce_auth(): app = Flask(__name__) app.config['AUTH_KEY'] = 'secretpassword' app.before_request(corral.util.enforce_auth) @app.route('/admin') def admin_panel(): return 'Admin panel.\n' with app.test_client() as c: rv = c.get('/admin') assert b'You must be authenticated' in rv.data assert rv.status_code == 403 rv = c.get('/admin', headers={'Cookie': 'key=secretpassword'}) assert rv.data == b'Admin panel.\n' assert rv.status_code == 200
def test_detect_auth(): app = Flask(__name__) app.config['AUTH_KEY'] = 'secretpassword' app.before_request(corral.util.detect_auth) @app.route('/checkauth') def check_auth(): return jsonify({'authed': g.authed}) with app.test_client() as c: rv = c.get('/checkauth') data = json.loads(rv.data.decode('utf-8')) assert data['authed'] == False rv = c.get('/checkauth', headers={'Cookie': 'key=secretpassword'}) data = json.loads(rv.data.decode('utf-8')) assert data['authed'] == True
def create_app(config_object=None): app = Flask(__name__) app.config.from_object('config.default') if config_object: app.config.from_object(config_object) app.add_url_rule('/', view_func=views.get_apps, methods=['GET']) app.add_url_rule('/login', view_func=views.get_login, methods=['GET']) app.add_url_rule('/login', view_func=views.do_login, methods=['POST']) app.add_url_rule('/logout', view_func=views.do_logout, methods=['GET']) app.add_url_rule('/deploy', view_func=views.do_deploy, methods=['POST']) app.add_url_rule('/ping/ping', view_func=views.healthcheck, methods=['GET']) app.register_error_handler(WBAPIHTTPError, views.wb_error_handler) app.register_error_handler(Exception, views.generic_error_handler) app.before_request(get_api_before_request) return app