def create_app(): print("STARTING") app = Flask(__name__, template_folder=template_dir) CORS(app) app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + PROJECT_ROOT + '/db/log.db' app.config['SQLALCHEMY_ECHO'] = True db.init_app(app) app.after_request(add_header) app.add_url_rule('/', view_func=IndexView.as_view('index')) app.add_url_rule("/notebook/", view_func=IndexView.as_view('index2')) app.add_url_rule("/notebook/<entry_id>", view_func=IndexView.as_view('index3')) app.add_url_rule("/sources/", view_func=IndexView.as_view('index4')) app.add_url_rule("/derivative-sources/", view_func=IndexView.as_view('index5')) app.add_url_rule("/api/sources", view_func=SourcesView.as_view('sources_view')) app.add_url_rule("/api/sources/<int:datasource_id>", view_func=SourcesView.as_view('source_view')) app.add_url_rule("/api/data", view_func=DataView.as_view('data_view')) app.add_url_rule("/api/annotations", view_func=AnnotationView.as_view('annotation_view')) app.add_url_rule("/api/derivative_source_definitions", view_func=DerivativeSourceDefinitionView.as_view( 'derivative_source_definitions_view')) app.add_url_rule( "/api/notebook/entries", view_func=NotebookEntriesView.as_view('notebook_entries_view')) app.add_url_rule( "/api/notebook/entries/<int:entry_id>", view_func=NotebookEntryView.as_view('notebook_entry_view')) return app
def create_app(run_mode=os.getenv('FLASK_ENV', 'production')): """Return a configured Flask App using the Factory method.""" app = Flask(__name__, template_folder='templates') app.config.from_object(CONFIGURATION[run_mode]) # Configure Sentry if str(app.config.get('SENTRY_ENABLE')).lower() == 'true': if app.config.get('SENTRY_DSN', None): sentry_sdk.init( dsn=app.config.get('SENTRY_DSN'), integrations=[FlaskIntegration()] ) from status_api.resources import API_BLUEPRINT, OPS_BLUEPRINT # pylint: disable=import-outside-toplevel app.register_blueprint(API_BLUEPRINT) app.register_blueprint(OPS_BLUEPRINT) app.after_request(convert_to_camel) ExceptionHandler(app) @app.after_request def add_version(response): # pylint: disable=unused-variable version = get_run_version() response.headers['API'] = f'status_api/{version}' return response register_shellcontext(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(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(config_class=Config): app = Flask(__name__) CORS(app) app.config.from_object(Config) db.init_app(app) migrate.init_app(app, db) from api.issues import bp as issues_bp app.register_blueprint(issues_bp, url_prefix='/api/issues') from api.health import bp as health_bp app.register_blueprint(health_bp, url_prefix='/api/health') if not app.debug and not app.testing: log = logging.StreamHandler(sys.stdout) formatter = logging.Formatter(('%(asctime)s - %(name)s - ' '%(levelname)s - %(message)s')) log.setFormatter(formatter) log.setLevel(logging.INFO) app.logger.addHandler(log) app.logger.setLevel(logging.INFO) app.after_request(insert_headers) return app
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
def create_app(config_obj=None): """ Create a Flask application object. :return: a Flask application object :rtype: flask.Flask """ app = Flask(__name__) if config_obj: app.config.from_object(config_obj) else: load_config(app) if app.config[ 'PRODUCTION'] and app.secret_key == 'replace-me-with-something-random': raise Warning( 'You need to change the app.secret_key value for production') # Set the Neo4j connection URI based on the Flask config neomodel_config.DATABASE_URL = app.config.get('NEO4J_URI') init_logging(app) for status_code in default_exceptions.keys(): app.register_error_handler(status_code, json_error) app.register_error_handler(ValidationError, json_error) app.register_error_handler(ServiceUnavailable, json_error) app.register_error_handler(AuthError, json_error) app.register_blueprint(api_v1, url_prefix='/api/v1') app.after_request(insert_headers) return app
def create_app(config_obj): app = Flask(__name__) app.config.from_object(config_obj) app.after_request(req_end) db.init_app(app) app.register_blueprint(blueprint, url_prefix='/api/v1') return app
def register_hooks(flask_app: Flask): from app.exceptions.exceptions import broad_exception_error_handler, http_exception_handler from app.hooks.request_hook import after_request flask_app.after_request(after_request) flask_app.register_error_handler(HTTPException, http_exception_handler) flask_app.register_error_handler(Exception, broad_exception_error_handler)
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=False) def include_raw(filename, squash=''): with app.open_resource('templates/{}'.format(filename), mode='r') as f: return Markup(f.read().replace('\n', squash)) def include_json(*filenames): data = {} for filename in filenames: with app.open_resource(os.path.join('templates', filename), mode='r') as f: data.update(json.loads(f.read())) return Markup(json.dumps(data, separators=[',', ':'])) @app.context_processor def inject_include_raw(): return dict(include_raw=include_raw, include_json=include_json) create_mustache_templates(app) @app.route('/') def index(): return render_template('index.html') if app.config['DEBUG']: app.after_request(bust_cache) register_assets(app) return app
def create_app(test_config=None): """ create and configure the app """ application = Flask(__name__, instance_relative_config=True) application.config.from_mapping(SECRET_KEY='dev', ) if test_config is None: # load the instance config, if it exists, when not testing application.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in application.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(application.instance_path) except OSError: pass from . import app from . import controls from . import calibration from . import viewer from . import api application.register_blueprint(app.bp) application.register_blueprint(controls.bp) application.register_blueprint(calibration.bp) application.register_blueprint(viewer.bp) application.register_blueprint(api.bp) application.before_first_request( partial(initialize, application.instance_path)) application.after_request(add_header) return application
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 create_app(configpath): app = Flask('Neuronal activity analyzer', template_folder='templates', static_folder='webgui/static') app.config.from_pyfile(configpath) app.secret_key = app.config['SECRET_KEY'] # Create folders if they don't exist folders = [ app.config['VIDEO_FOLDER'], app.config['UPLOAD_FOLDER'], app.config['DATA_FOLDER'] ] for folder in folders: if not os.path.isdir(folder): os.mkdir(folder) app.register_blueprint(main_blueprint) app.register_blueprint(file_select_blueprint) app.register_blueprint(segmentation_blueprint) app.register_blueprint(roi_editor_blueprint) app.register_blueprint(statistics_blueprint) app.register_blueprint(batch_blueprint) app.after_request(disable_cache) app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False compress.init_app(app) return app
def _register_after_request(app: Flask): encoder = app.json_encoder() def after_request(response: Response): """ A function to run after each request. """ execution_time = time.time() - g.start_time try: logger.debug({ "url_rule": request.url_rule, "execution_time": execution_time, "request_id": g.request_id, "request": { "method": request.method, "url": request.url, "payload": encoder.encode(request.json) if request.is_json and request.json and len( request.data) > 0 else "" }, "response": { "status": response.status, "payload": encoder.encode(response.json) if response.is_json and response.json and len( response.data) > 0 else "" } }) except Exception as e: # Log Exception but otherwise don't do anything since we don't want to fail a customer request b/c our # logging is broken logger.error(e) return response app.after_request(after_request)
def create_app(run_mode=os.getenv('FLASK_ENV', 'production')): """Return a configured Flask App using the Factory method.""" app = Flask(__name__) app.config.from_object(config.CONFIGURATION[run_mode]) from pay_api.resources import API_BLUEPRINT, OPS_BLUEPRINT db.init_app(app) ma.init_app(app) app.register_blueprint(API_BLUEPRINT) app.register_blueprint(OPS_BLUEPRINT) app.after_request(convert_to_camel) setup_jwt_manager(app, jwt) ExceptionHandler(app) @app.after_request def add_version(response): # pylint: disable=unused-variable version = get_run_version() response.headers['API'] = f'pay_api/{version}' return response register_shellcontext(app) return app
def create_app(): """ 生成app实例 :return: """ flask_app = Flask(__name__) flask_app.config.from_object('configs') init_logging(flask_app) if configs.DEBUG: def after_request(resp): # Enable CORS supported resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers[ 'Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS' resp.headers['Access-Control-Allow-Credentials'] = True resp.headers['Access-Control-Max-Age'] = 1728000 resp.headers['Access-Control-Allow-Headers'] = ( 'DNT,X-Custom-Header,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,' 'Content-Type,Authorization') return resp flask_app.after_request(after_request) add_url_rules_and_register_blueprints('application.views', flask_app) action_before_app_run(flask_app) return flask_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(run_mode=os.getenv('FLASK_ENV', 'production')): """Return a configured Flask App using the Factory method.""" app = Flask(__name__) app.config.from_object(CONFIGURATION[run_mode]) app.logger.setLevel(logging.INFO) # pylint: disable=no-member db.init_app(app) app.json_encoder = CustomJSONEncoder if app.debug: migrate = Migrate(app, db) # noqa # pylint: disable=unused-variable CORS(app) # Configure Sentry if app.config.get('SENTRY_DSN', None): sentry_sdk.init( dsn=app.config.get('SENTRY_DSN'), integrations=[FlaskIntegration()] ) app.register_blueprint(DIRECTORS_API) app.register_blueprint(BUSINESSES_API) app.register_blueprint(OPS_API) app.register_blueprint(AUTH_API) app.after_request(convert_to_camel) if not app.config.get('BENCHMARK', None): setup_jwt_manager(app, jwt) 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 register_after_request_handlers(application: Flask) -> None: """ Register handlers that will be executed after each request. :param application: The application instance for which the handlers will be registered. """ application.after_request(_header_x_clacks_overhead)
def register_middleware(app: Flask): @app.before_request def before_request(): print(request.method, request.endpoint) from .middlewares.args import args app.after_request(args)
def create_app(*config_cls): print('[INFO] Flask application initialized with {}'.format([config.__name__ for config in config_cls])) app_ = Flask( __name__, static_folder='{}/static'.format(WEB_FILE_ROOT_DIR), template_folder='{}/templates'.format(WEB_FILE_ROOT_DIR) ) for config in config_cls: app_.config.from_object(config) connect(**app_.config['MONGODB_SETTINGS']) cfg = app_.config JWTManager().init_app(app_) CORS().init_app(app_) Swagger(template=app_.config['SWAGGER_TEMPLATE']).init_app(app_) Router().init_app(app_) app_.after_request(after_request) app_.register_error_handler(Exception, exception_handler) return app_
def create_app(): # initialize app app = Flask(__name__) # configure app app.config.from_object('config.' + app.config['ENV'].title() + 'Config') # configure loggings dictConfig( yaml.safe_load(open('logging_config.yaml', 'r'))[app.config['ENV']]) logging.getLogger('sqlalchemy').propagate = False # initialize db # db.init_app(app) # initialize cache cache.init_app(app) # register blueprints app.register_blueprint(apiv1) # after request global app.after_request(_app_after_request) # connect signals request_started.connect(_request_started_handler, app) request_finished.connect(_request_finished_handler, app) return app
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 init_hooks(app: Flask): @app.before_first_request def set_current_celery_app(): """Listener for `before_first_request`. Set our celery app as current, so that task use the correct config. Without that tasks may use their default set app. """ celery = app.extensions.get("celery") if celery: celery.set_current() @app.before_first_request def register_signals(): signals.register_js_api.send(app) # def install_id_generator(sender, **kwargs): # g.id_generator = count(start=1) # # appcontext_pushed.connect(install_id_generator) if os.environ.get("FLASK_VALIDATE_HTML"): # Workaround circular import from abilian.testing.validation import validate_response app.after_request(validate_response)
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(settings_override=None): """ Create a Flask application using the app factory pattern. :param settings_override: Override settings :return: Flask app """ app = Flask(__name__, instance_relative_config=True) def disable_varnish(response): response.cache_control.private = True return response app.after_request(disable_varnish) SSLify(app, skips=['healthcheck']) gunicorn_logger = logging.getLogger('gunicorn.error') app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.config.from_object('config.settings') if 'GOOGLE_CLIENT_ID' in app.config: setup_authentication(app) app.register_blueprint(page) plugins = {} for plugin in app.config['ENABLED_PLUGINS']: module = importlib.import_module(f'dashboard.plugins.{plugin}') app.register_blueprint(module.plugin, url_prefix=module.base_path) plugins[plugin] = {'tab_name': module.tab_name} app.airflow_data_provider = AirflowDBDataProvider( app.config, app.logger, MySQLClient(app.config, app.logger)) app.influx_data_provider = InfluxDBData( app.config, app.logger) if app.config.get('INFLUXDB_HOST') else None app.prometheus_data_provider = PrometheusData( app.config, app.logger) if app.config.get('PROMETHEUS_HOST') else None # Reading tables configs, setting variable to `None` if file is not present tables = get_yaml_file_content(TABLES_PATH) app.table_data_provider = TableDataProvider( app.airflow_data_provider, app.influx_data_provider, app.prometheus_data_provider, tables, app.logger, app.config) if tables else None app.etl_data_provider = EtlDataProvider(app.config, app.airflow_data_provider, app.table_data_provider) app.async_request_executor = ThreadPoolExecutor(max_workers=3) app.cache = SimpleCache() if app.debug: app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) app.context_processor(lambda: {'now': datetime.now(), 'plugins': plugins}) 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): """ Create a Flask app with a registered API and namespaces """ flask_app = Flask('timezone_keeper') flask_app.config.from_object(FlaskCfgObject(config)) blueprint = Blueprint('api', __name__, url_prefix=API_PREFIX) flask_api.init_app(blueprint) flask_api.add_namespace(auth_ns) flask_api.add_namespace(user_ns) flask_api.add_namespace(role_ns) flask_api.add_namespace(timezone_ns) if 'api' not in flask_app.blueprints: flask_app.register_blueprint(blueprint) log.info('Database path: %s', config.SQLALCHEMY_DATABASE_URI) db.init_app(flask_app) jwt = flask_jwt_extended.JWTManager(flask_app) jwt.user_claims_loader(jwt_add_claims_to_access_token) jwt.user_identity_loader(jwt_user_identity_lookup) jwt.token_in_blacklist_loader(jwt_check_blacklisted) flask_app.after_request(add_cors_headers) return flask_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 init_hooks(app: Flask) -> None: @app.before_first_request def set_current_celery_app() -> None: """Listener for `before_first_request`. Set our celery app as current, so that task use the correct config. Without that tasks may use their default set app. """ celery = app.extensions.get("celery") if celery: celery.set_current() @app.before_first_request def register_signals() -> None: signals.register_js_api.send(app) # def install_id_generator(sender, **kwargs): # g.id_generator = count(start=1) # # appcontext_pushed.connect(install_id_generator) if os.environ.get("FLASK_VALIDATE_HTML"): # Workaround circular import from abilian.testing.validation import validate_response app.after_request(validate_response)
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(configpath): app = Flask('Neuronal activity analyzer', template_folder='templates', static_folder='webgui/static') app.config.from_pyfile(configpath) app.secret_key = app.config['SECRET_KEY'] # Create folders if they don't exist folders = [app.config['VIDEO_FOLDER'], app.config['UPLOAD_FOLDER'], app.config['DATA_FOLDER']] for folder in folders: if not os.path.isdir(folder): os.mkdir(folder) app.register_blueprint(main_blueprint) app.register_blueprint(file_select_blueprint) app.register_blueprint(segmentation_blueprint) app.register_blueprint(roi_editor_blueprint) app.register_blueprint(statistics_blueprint) app.register_blueprint(batch_blueprint) app.after_request(disable_cache) app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False compress.init_app(app) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.register_blueprint(main_bp) app.after_request(after_request) return app
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_cls): """ Create and initialize Flask instance """ app_ = Flask( __name__, static_folder='{}/static'.format('../app'), static_url_path='/', template_folder='{}/static'.format('../app') ) for config in config_cls: app_.config.from_object(config) CORS().init_app(app_) JWTManager().init_app(app_) Swagger(template=app_.config['SWAGGER_TEMPLATE']).init_app(app_) Router().init_app(app_) db.init_app(app_) db.create_all(app=app_) app_.after_request(after_request) app_.register_error_handler(Exception, error_handler) @app_.route('/') def index(): return render_template('index.html') return app_
def create_app(run_mode=os.getenv('FLASK_ENV', 'production')): """Return a configured Flask App using the Factory method.""" app = Flask(__name__) app.config.from_object(config.CONFIGURATION[run_mode]) db.init_app(app) ma.init_app(app) if run_mode != 'migration': # Configure Sentry if app.config.get('SENTRY_DSN', None): # pragma: no cover sentry_sdk.init(dsn=app.config.get('SENTRY_DSN'), integrations=[FlaskIntegration()]) # pylint: disable=import-outside-toplevel from pay_api.resources import API_BLUEPRINT, OPS_BLUEPRINT app.register_blueprint(API_BLUEPRINT) app.register_blueprint(OPS_BLUEPRINT) app.after_request(convert_to_camel) setup_jwt_manager(app, jwt) ExceptionHandler(app) @app.after_request def add_version(response): # pylint: disable=unused-variable version = get_run_version() response.headers['API'] = f'pay_api/{version}' return response register_shellcontext(app) build_cache(app) return app
class FlaskApp: def __init__(self, name): self.flask_app = Flask(name) # enable CORS self.flask_app.after_request(self._after_request) self._create_rules() def run(self): self.flask_app.run() def _after_request(self, resp): h = resp.headers # prepare headers for CORS authentication h['Access-Control-Allow-Origin'] = '*' resp.headers = h print(resp.headers) return resp def _create_rules(self): self.flask_app.add_url_rule('/session/', view_func=SessionsView.as_view('sessions')) self.flask_app.add_url_rule('/session/<session_id>/file/', view_func=SessionFileView.as_view('session_files')) self.flask_app.add_url_rule('/session/<session_id>/file/<file_id>', view_func=IterationsView.as_view('file_iterations'))
def create_app(config): app = Flask(__name__) app.config.update(config) app.after_request(add_cors_header) db.app = app db.init_app(app) # Test API for Tracks api = Api(app) import wpws.waveplot import wpws.track import wpws.recording import wpws.release import wpws.medium import wpws.artist_credit wpws.waveplot.create_api(api) wpws.track.create_api(api) wpws.recording.create_api(api) wpws.release.create_api(api) wpws.medium.create_api(api) wpws.artist_credit.create_api(api) return app
def main(): app = Flask(__name__) @app.route("/page/<id>") def display_message(id): stat_server.users_stat() return "Page ID is {} !".format(id) app.after_request(log_status_code) # the parameter function will run app.run(debug=True) # after each request
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 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): """ 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 create_app(config_filename='config.yaml'): app = Flask(__name__) app.response_class = TextResponse app.url_map.converters['sid'] = SIDConverter app.url_map.converters['sha1'] = SHA1Converter app.url_map.converters['label'] = LabelConverter load_yaml(app, config_filename) init_db(app) init_cache(app) app.after_request(cors) app.register_blueprint(paste) return app
def create_app(config): app = Flask(__name__) app.config.update(config) app.after_request(add_cors_header) global db db.app = app db.init_app(app) global manager manager.init_app(app, flask_sqlalchemy_db=db) manager.create_api(ws.schema.Annotation, methods=['GET']) manager.create_api(ws.schema.Application, methods=['GET']) manager.create_api(ws.schema.Area, methods=['GET'], primary_key='gid') manager.create_api(ws.schema.AreaType, methods=['GET']) manager.create_api(ws.schema.Artist, methods=['GET'], primary_key='gid') manager.create_api(ws.schema.ArtistType, methods=['GET']) manager.create_api(ws.schema.ArtistCredit, methods=['GET']) manager.create_api(ws.schema.Edit, methods=['GET']) manager.create_api(ws.schema.Editor, methods=['GET']) manager.create_api(ws.schema.Gender, methods=['GET']) manager.create_api(ws.schema.Language, methods=['GET']) manager.create_api(ws.schema.Recording, methods=['GET']) manager.create_api(ws.schema.Release, methods=['GET'], primary_key='gid', include_methods=['url']) manager.create_api(ws.schema.ReleasePackaging, methods=['GET']) manager.create_api(ws.schema.ReleaseStatus, methods=['GET']) manager.create_api(ws.schema.ReleaseGroup, methods=['GET'], primary_key='gid') manager.create_api(ws.schema.ReleaseGroupPrimaryType, methods=['GET'], primary_key='gid') manager.create_api(ws.schema.Script, methods=['GET']) manager.create_api(ws.schema.Work, methods=['GET']) manager.create_api(ws.schema.WorkType, methods=['GET']) return app
def create_app(config): app = Flask(__name__) app.config.update(config) app.after_request(add_cors_header) db.app = app db.init_app(app) mail.init_app(app) from .index import index_views app.register_blueprint(index_views, url_prefix='/internal') from .registration import registration_views app.register_blueprint(registration_views, url_prefix='/internal') return app
def run_app(): app = Flask(__name__) app.config.from_object(__name__) app.after_request(add_cors_header) """ Returns the list of (time, location) for all the meals To test using curl, try this command: curl -H "Content-Type: application/json" -X POST -d '{"start": "Providence, RI", "end": "San Francisco, CA", "date":"2011-12-01T12:00:00.00Z"}' http://127.0.0.1:5000/journey """ @app.route('/journey', methods=["GET", "POST"]) def journey(): start = request.json["start"] end = request.json["end"] d = datetime.strptime(request.json["date"], '%Y-%m-%dT%H:%M:%S.%fZ') if request.json["date"] != None else datetime.datetime.today() meals = maps.getMeals(start, end, d) return json.dumps(meals, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x) """ Returns a dict, containing: { "path": A polyline, defined as [{latitude: int, longitude: int} ... ], "locations":[(timestamp, coordinate) ...] } To test using curl, try this command: curl -H "Content-Type: application/json" -X POST -d '{"start": "Providence, RI", "end": "San Francisco, CA", "date":"2011-12-01T12:00:00.00Z"}' http://127.0.0.1:5000/journeyWithPath """ @app.route('/journeyWithPath', methods=["GET", "POST"]) def journeyWithPath(): start = request.json["start"] end = request.json["end"] d = datetime.strptime(request.json["date"], '%Y-%m-%dT%H:%M:%S.%fZ') if request.json["date"] != None else datetime.datetime.today() meals = maps.getMealsAndPath(start, end, d) return json.dumps(meals, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x) """ To test using curl, try this command: curl -H "Content-Type: application/json" -X POST -d '{"lat": 41.8236, "lng": -71.4222}' http://127.0.0.1:5000/restaurants """ @app.route('/restaurants', methods=["GET", "POST"]) def restaurants(): coords = request.json rests = get_restaurants_from_coordinate(coords) return json.dumps(rests, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else x) app.run()
def create_application(name = __name__, env = 'testing'): app = Flask(__name__, static_path = '/static') # Load our default configuration load_configuration(app, env) # Setup Mail mail.init_app(app) # Setup OAuth2 Provider oauth.init_app(app) # Load our application's blueprints load_blueprints(app) rq.init_app(app) """ Setup Flask Security We cannot load the security information until after our blueprints have been loaded into our application. """ from CommonsCloudAPI.models.user import user_datastore security.init_app(app, user_datastore) # Initialize our database and create tables db.init_app(app) db.app = app db.create_all() # Load default application routes/paths load_errorhandlers(app) def add_cors_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS' response.headers['Access-Control-Allow-Headers'] = 'Authorization, Accept, Content-Type, X-Requested-With, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Cache-Control, Expires, Set-Cookie' response.headers['Access-Control-Allow-Credentials'] = True return response app.after_request(add_cors_header) return app
def create_app(): app = Flask(__name__) app.config.from_object('polipoly2.default_settings') app.config.from_envvar('POLIPOLY2_SETTINGS', silent=True) register_converters(app) init_engine(app.config['DATABASE_URI']) def shutdown_session(response): session.remove() return response app.after_request(shutdown_session) from polipoly2.views import views app.register_module(views) return app
def create_app(config_name): """ Flask app factory """ app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) api = Api() db.init_app(app) from .resources import MonsterResource, MonsterListResource api.add_resource(MonsterListResource, '/monsters', endpoint='monsters') api.add_resource(MonsterResource, '/monster/<int:id>', endpoint='monster') api.init_app(app) app.after_request(add_cors_headers) return app
def create_app(config_file): """ Create the webservice application using the configuration provided in config_file, and initialize SQLAlchemy, Redis and OAuth services. Also installs webservice routes. """ app = Flask(__name__.split(".")[0]) app.config.from_pyfile(config_file) app.after_request(add_cors_header) # Initialize Flask extensions api = Api(app) db.init_app(app) cache.init_app(app) oauth_provider.init_app(app) # Initialize OAuth handler import bbws.oauth bbws.oauth.init(app) # Initialize custom endpoints import bbws.custom bbws.custom.init(app) # Initialize webservice routes import bbws.entity import bbws.revision import bbws.user import bbws.entityspecific import bbws.relationship import bbws.musicbrainz bbws.entity.create_views(api) bbws.revision.create_views(api) bbws.user.create_views(api) bbws.entityspecific.create_views(api) bbws.relationship.create_views(api) bbws.musicbrainz.create_views(api) return app
def create_app(config_obj=None): """ Create a Flask application object. :return: a Flask application object :rtype: flask.Flask """ app = Flask(__name__) if config_obj: app.config.from_object(config_obj) else: load_config(app) if app.config['ENV'] != 'development': if app.config['SECRET_KEY'] == 'replace-me-with-something-random': raise RuntimeError('You need to change the SECRET_KEY configuration for production') for config in ('AD_DOMAIN', 'AD_LDAP_URI', 'AD_USERS_GROUP', 'AD_ADMINS_GROUP', 'AD_SERVICE_USERNAME', 'AD_SERVICE_PASSWORD', 'SQLALCHEMY_DATABASE_URI'): if not app.config.get(config): raise RuntimeError('You need to set the "{0}" setting'.format(config)) init_logging(app) db.init_app(app) migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrations') Migrate(app, db, directory=migrations_dir) app.cli.command()(create_db) for status_code in default_exceptions.keys(): app.register_error_handler(status_code, json_error) app.register_error_handler(ValidationError, json_error) app.register_error_handler(ConfigurationError, json_error) app.register_error_handler(ADError, json_error) app.after_request(insert_headers) app.register_blueprint(api_v1, url_prefix='/api/v1') jwt = JWTManager(app) jwt.token_in_blacklist_loader(BlacklistedToken.is_token_revoked) jwt.user_claims_loader(add_jwt_claims) app.cli.command()(prune_blacklisted_tokens) return 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: komoo_app = create_app(my_config_obj) komoo_app.run() """ app = Flask('komoo') app.config.from_object(config) db = config.get_db() # flush pending mongodb requests def call_end_request(response): db.connection.end_request() return response # makes possible to access the db directly from any view # (possible, but **not encouraged**, avoid doing this) def add_db_to_request(): g.db = db app.before_request(add_db_to_request) app.after_request(call_end_request) # register all blueprints for bp in blueprints: app.register_blueprint(bp[0], url_prefix=bp[1]) return app
def app(self): """ derive flask app based on the combination of command-line options and the contents of the .ini files """ ## set flask specific things that are non-optional error = lambda k: 'Fatal: You need to specify a "flask" section ' + \ 'with an entry like "'+k+'=..." in your .ini file' try: app_name = self['flask.app'] except KeyError: raise SystemExit(error('app')) try: secret_key = self['flask.secret_key'] except KeyError: raise SystemExit(error('secret_key')) app = Flask(app_name) app.secret_key = secret_key ## set flask specific things that are optional if 'flask.template_path' in self: app.jinja_loader = FileSystemLoader(self['template_path']) if 'flask.before_request' in self: before_request = self['flask.before_request'] before_request = namedAny(before_request) app.before_request(before_request) if 'flask.after_request' in self: after_request = self['flask.after_request'] after_request = namedAny(after_request) app.after_request(after_request) ## setup views try: view_holder = self['corkscrew.views'] except KeyError: error = 'Fatal: could not "view=<dotpath>" entry in your .ini file' raise SystemExit(error) else: view_list = namedAny(view_holder) [ v(app=app, settings=self) for v in view_list] return app
redis_server = redis.StrictRedis( host=redis_url.hostname, port=redis_url.port, password=redis_url.password ) store = RedisStore(redis_server) kv_store = KVSessionExtension(store, app) Health(app, checks=[db.health]) # Audit, error handling and after_request headers all handled by lrutils Audit(app) ErrorHandler(app) app.after_request(eh_after_request) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) app.logger.debug("\nConfiguration\n%s\n" % app.config)
app.register_blueprint(shield_code, url_prefix="/shield") app.register_blueprint(donate_coin, url_prefix="/donate") app.register_blueprint(izhero_story, url_prefix="/izstory") app.register_blueprint(coinlog, url_prefix="/coinlog") app.register_blueprint(comic_shelf, url_prefix="/comic") app.register_blueprint(gallery_sticker, url_prefix="/gallery") app.register_blueprint(izhero_ann, url_prefix="/news") app.register_blueprint(game_shelf, url_prefix="/games") app.register_blueprint(iz_encyclopedia, url_prefix="/encyclopedia") app.register_blueprint(iz_encycloarticle, url_prefix="/encyclopedia/pages") app.register_blueprint(facebook, url_prefix="/share") app.register_blueprint(card_shelf, url_prefix="/cards") app.register_blueprint(dqmission_progress, url_prefix="/dqmissions") app.register_blueprint(survey, url_prefix="/dqsurveys/item") app.register_blueprint(answer, url_prefix="/dqsurveys/answer") app.register_blueprint(dq_messenger, url_prefix="/messengers") app.register_blueprint(dq_messengerlog, url_prefix="/messages") app.register_blueprint(izhero_sub, url_prefix="/subscribe") app.register_blueprint(survey_rcode, url_prefix="/dqresult") app.register_blueprint(api_member, url_prefix="/memberships") app.after_request(nocache) Auth(app, is_mgo=True, userdb="IZHero", loader_name="user.js", loader_full=True, bp_prefix="/acct") Upload(app, public_folders=["stickers", "comics", "encyclopedia", "lessons", "resources", "certificate"]) Drawing(app) Certificate(app) app.mandrill = Mandrill(app) if __name__ == "__main__": raise Exception('Execute run.py instead')
def create_app(): from config import configs application = Flask(__name__) application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]]) init_app(application) statsd_client.init_app(application) logging.init_app(application, statsd_client) init_csrf(application) request_id.init_app(application) service_api_client.init_app(application) user_api_client.init_app(application) api_key_api_client.init_app(application) job_api_client.init_app(application) notification_api_client.init_app(application) status_api_client.init_app(application) invite_api_client.init_app(application) template_statistics_client.init_app(application) events_api_client.init_app(application) provider_client.init_app(application) organisations_client.init_app(application) login_manager.init_app(application) login_manager.login_view = "main.sign_in" login_manager.login_message_category = "default" login_manager.session_protection = None from app.main import main as main_blueprint application.register_blueprint(main_blueprint) from .status import status as status_blueprint application.register_blueprint(status_blueprint) proxy_fix.init_app(application) application.session_interface = ItsdangerousSessionInterface() application.add_template_filter(format_datetime) application.add_template_filter(format_datetime_24h) application.add_template_filter(format_datetime_normal) application.add_template_filter(format_datetime_short) application.add_template_filter(format_time) application.add_template_filter(syntax_highlight_json) application.add_template_filter(valid_phone_number) application.add_template_filter(linkable_name) application.add_template_filter(format_date) application.add_template_filter(format_date_normal) application.add_template_filter(format_date_short) application.add_template_filter(format_datetime_relative) application.add_template_filter(format_delta) application.add_template_filter(format_notification_status) application.add_template_filter(format_notification_status_as_time) application.add_template_filter(format_notification_status_as_field_status) application.add_template_filter(format_notification_status_as_url) application.after_request(useful_headers_after_request) application.after_request(save_service_after_request) application.before_request(load_service_before_request) @application.context_processor def _attach_current_service(): return {"current_service": current_service} register_errorhandlers(application) setup_event_handlers() return application
def create_app(config='config.ProductionDevelopmentConfig', apptype='profi'): app = Flask(__name__, static_folder='./static') app.config.from_object(config) app.teardown_request(close_database) app.debug = app.config['DEBUG'] if 'DEBUG' in app.config else False app.testing = app.config['TESTING'] if 'TESTING' in app.config else False app.before_request(load_database(app.config['SQLALCHEMY_DATABASE_URI'])) app.before_request(lambda: load_user(apptype)) app.before_request(setup_authomatic(app)) def add_map_headers_to_less_files(response): response.headers.add('Access-Control-Allow-Origin', '*') if request.path and re.search(r'\.css$', request.path): mapfile = re.sub(r'\.css$', r'.css.map', request.path) if os.path.isfile(os.path.realpath(os.path.dirname(__file__)) + mapfile): response.headers.add('X-Sourcemap', mapfile) return response app.after_request(add_map_headers_to_less_files) @login_manager.user_loader def load_user_manager(user_id): return g.db.query(User).get(user_id) # if apptype in ['file', 'profi', 'static', 'front']: session_opts = { 'session.type': 'ext:memcached', 'session.cookie_domain': '.' + Config.MAIN_DOMAIN, 'session.url': 'memcached.profi:11211' } class BeakerSessionInterface(SessionInterface): def open_session(self, app, request): return request.environ.get('beaker.session') def save_session(self, app, session, response): session.save() app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts) app.session_interface = BeakerSessionInterface() app.type = apptype login_manager.init_app(app) login_manager.session_protection = 'basic' if apptype == 'front': # relative paths def join_path(template, parent): return os.path.join(os.path.dirname(parent), template) app.jinja_env.join_path = join_path def load_portal(): from profapp.models.portal import Portal portal = g.db.query(Portal).filter_by(host=request.host).first() g.portal = portal if portal else None g.portal_id = portal.id if portal else None g.portal_layout_path = portal.layout.path if portal else '' g.lang = g.portal.lang if g.portal else g.user_dict['lang'] if portal else 'en' app.before_request(load_portal) from profapp.controllers.blueprints_register import register_front as register_blueprints_front register_blueprints_front(app) update_jinja_engine(app) @app.errorhandler(404) def page_not_found(e): from flask import Flask, render_template from profapp.controllers.views_front import error_404 return error_404() elif apptype == 'static': from profapp.controllers.blueprints_register import register_static as register_blueprints_static register_blueprints_static(app) elif apptype == 'file': from profapp.controllers.blueprints_register import register_file as register_blueprints_file register_blueprints_file(app) else: from profapp.controllers.blueprints_register import register_profi as register_blueprints_profi register_blueprints_profi(app) update_jinja_engine(app) if apptype in ['profi', 'front']: bootstrap.init_app(app) mail.init_app(app) return app
def render_rst(content): input_file = StringIO(content) parser = ReStructuredTextParser() document_tree = parser.parse(input_file) document = Article(document_tree, OPTIONS, backend=pdf) pdf_output = BytesIO() document.render(file=pdf_output) pdf_output.seek(0) return pdf_output ALLOW_ORIGIN = '*' if DEV_MODE else 'http://www.opqode.com' def article_allow_origin(response): if request.path == '/wake': response.headers.add('Access-Control-Allow-Origin', ALLOW_ORIGIN) return response app.after_request(article_allow_origin) if __name__ == '__main__': app.run(debug=True) else: os.chdir(os.path.dirname(__file__))
app = Flask(__name__) heroku = Heroku(app) db = SQLAlchemy(app) make_class_dictable(db.Model) # ------------------- # Settings # ------------------- def add_cors_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type' response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS' return response app.after_request(add_cors_header) # ------------------- # Types # ------------------- class JsonType(Mutable, types.TypeDecorator): ''' JSON wrapper type for TEXT database storage. References: http://stackoverflow.com/questions/4038314/sqlalchemy-json-as-blob-text http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/mutable.html ''' impl = types.Unicode