def create_app(): """ Create the application and return it to the user :return: flask.Flask application """ app = Flask(__name__) app.url_map.strict_slashes = False # Load config and logging Consul(app) # load_config expects consul to be registered load_config(app) logging.config.dictConfig( app.config['SYSTEMSGO_LOGGING'] ) # Cache cache.init_app(app, config=app.config['CACHE']) # CORS CORS( app, resource={ r'/status': {'origins': app.config['CORS_ORIGINS']} } ) # Register extensions api = Api(app) # Add end points api.add_resource(IndexView, '/') api.add_resource(HomeView, '/status') return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.register_blueprint(main_blueprint) Misaka(app, tables=True, wrap=True) cache.init_app(app) return app
def create_app(): from cache import cache requests.packages.urllib3.add_stderr_logger() app = Flask(__name__) app.config.from_object('config.settings') try: app.config.from_envvar('ASTROLOLO_SETTINGS') print("Loaded config from envvar ASTROLOLO_SETTINGS") except: app.config.from_object('config.development') print("Loaded DEVELOPMENT config") cache.init_app(app, config={ 'CACHE_TYPE': 'simple', # 'CACHE_DIR': '.flask-cache', 'CACHE_THRESHOLD': 1000000, 'CACHE_DEFAULT_TIMEOUT': 60*60*60*24, # one day }) return app
def create_app(app_name='dcsqa', config='config.DevelopmentConfig'): app.config.from_object(config) cache.init_app(app) # register blueprint for each restful entry # http://flask.pocoo.org/docs/0.10/blueprints/ app.register_blueprint(criteria_blueprint, url_prefix=_get_url_prefix('criteria')) app.register_blueprint(raw_blueprint, url_prefix=_get_url_prefix('raw')) app.register_blueprint(result_blueprint, url_prefix=_get_url_prefix('result')) return app
def create_app(config_name='default'): app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY', '123456') # Initalizes the Cache cache.init_app(app) # Configure the Routes configure_blueprints(app) MONGODB_URI = os.environ.get( "MONGOLAB_URI", 'mongodb://localhost/honorroll') mongo_client = connect(host=MONGODB_URI) if os.environ.get("AWS", False): set_up_logging() return app
def create_app(settings_file): app = Flask(__name__) app.config.from_pyfile(settings_file) cache.init_app(app) mail = Mail() csrf = CsrfProtect() csrf.init_app(app) db.init_app(app) toolbar = DebugToolbarExtension() toolbar.init_app(app) app.mail = mail mail.init_app(app) app.hashids = Hashids(salt="salty seafaring sailor", min_length=8) register_errorhandlers(app) app.register_blueprint(main) return app
cachedir = join(environ["OPENSHIFT_DATA_DIR"],"cache") #clear cache if exists(cachedir): rmtree(cachedir) makedirs(cachedir) app.config['CACHE_DIR'] = cachedir #set timeout to about a month, as content only changes on push, and we clear #the cache then. This results in a lazy static site generator app.config['CACHE_TYPE'] = 'filesystem' app.config['CACHE_DEFAULT_TIMEOUT'] = 3000000 app.config['SECRET_KEY'] = getenv('OPENSHIFT_SECRET_TOKEN','development_token') cache.init_app(app) assets = Environment(app) assets.register('css',Bundle('source/style.less',depends='source/*.less',filters=['less','cleancss']),output='css/style.css') assets.register('js',Bundle('js/jquery-2.1.1.min.js','js/bootstrap.min.js'),output='js/all.js') app.register_blueprint(main) app.register_blueprint(blog) app.register_blueprint(docs) app.register_blueprint(parts) app.register_blueprint(search) app.register_blueprint(rest) babel = Babel(app,default_domain=website.translation.messages_domain)
def main(): cache.init_app(app) with app.app_context(): cache.clear() print "Cleared cache"
def make_app(config=None, **kw): "factory to create the app" app = ChillFlask('chill') if config: config_file = config if config[0] == os.sep else os.path.join(os.getcwd(), config) app.config.from_pyfile(config_file) app.config.update(kw) cache.init_app(app) # Set the freezer destination path to be absolute if needed. freeze_folder = app.config.get('FREEZER_DESTINATION', None) if freeze_folder: if freeze_folder[0] != os.sep: freeze_folder = os.path.join(os.getcwd(), freeze_folder) app.config['FREEZER_DESTINATION'] = freeze_folder # TODO: fix conflict with page_uri root_folder = app.config.get('ROOT_FOLDER', None) if root_folder: if root_folder[0] != os.sep: root_folder = os.path.join(os.getcwd(), root_folder) app.config['ROOT_FOLDER'] = root_folder #root_path = '/' # See no need to have this be different if os.path.isdir( root_folder ): app.add_url_rule('/<path:filename>', view_func=app.send_root_file) media_folder = app.config.get('MEDIA_FOLDER', None) if media_folder: if media_folder[0] != os.sep: media_folder = os.path.join(os.getcwd(), media_folder) app.config['MEDIA_FOLDER'] = media_folder media_path = app.config.get('MEDIA_PATH', '/media/') if os.path.isdir( media_folder ) and media_path[0] == '/': app.add_url_rule('%s<path:filename>' % media_path, view_func=app.send_media_file) document_folder = app.config.get('DOCUMENT_FOLDER', None) if document_folder: if document_folder[0] != os.sep: document_folder = os.path.join(os.getcwd(), document_folder) app.config['DOCUMENT_FOLDER'] = document_folder template_folder = app.config.get('THEME_TEMPLATE_FOLDER', app.template_folder) app.config['THEME_TEMPLATE_FOLDER'] = template_folder if template_folder[0] == os.sep else os.path.join(os.getcwd(), template_folder) queries_folder = app.config.get('THEME_SQL_FOLDER', 'queries') app.config['THEME_SQL_FOLDER'] = queries_folder if queries_folder[0] == os.sep else os.path.join(os.getcwd(), queries_folder) chill_queries_folder = os.path.join( os.path.dirname(__file__), 'queries' ) user_queries_folder = app.config.get('THEME_SQL_FOLDER') app.queries = multiple_directory_files_loader(chill_queries_folder, user_queries_folder) # Set the jinja2 template folder eith fallback for app.template_folder app.jinja_env.loader = FileSystemLoader( app.config.get('THEME_TEMPLATE_FOLDER') ) @app.teardown_appcontext def teardown_db(exception): db = getattr(g, '_database', None) if db is not None: db.close() # STATIC_URL='http://cdn.example.com/whatever/works/' @app.context_processor def inject_paths(): """ Inject the variables 'theme_static_path' and 'media_path' into the templates. Template variable will always have a trailing slash. """ theme_static_path = app.config.get('THEME_STATIC_PATH', '/theme/') media_path = app.config.get('MEDIA_PATH', '/media/') #static_url = app.config.get('STATIC_URL', app.static_url_path) if not theme_static_path.endswith('/'): theme_static_path += '/' if not media_path.endswith('/'): media_path += '/' return dict( theme_static_path=theme_static_path, media_path=media_path ) @app.context_processor def inject_config(): """ Inject the config into the templates. """ return dict(config=dict(app.config)) # Add the markdown filter for the templates md = Markdown(app) @app.template_filter('readfile') def readfile(filename): "A template filter to read files from the DOCUMENT_FOLDER" document_folder = app.config.get('DOCUMENT_FOLDER') if document_folder: # Restrict access to just the DOCUMENT_FOLDER. filepath = os.path.normpath(os.path.join(document_folder, filename)) if os.path.commonprefix([document_folder, filepath]) != document_folder: app.logger.warn("The filepath: '{0}' is outside of the DOCUMENT_FOLDER".format(filepath)) return filename with open(os.path.join(document_folder, filename), 'r') as f: content = f.read().decode('utf-8') return content app.logger.warn("jinja2 filter 'readfile' can't find file: '{0}'".format(filename)) return filename # register any blueprints here #app.logger.warning("Not registering resource blueprint") #app.register_blueprint(resource) from chill.public import PageView #app.logger.warning("Not registering page blueprint") page = Blueprint('public', __name__, static_folder=None, template_folder=None) # TODO: The shortcode start and end is rather custom. Make this # configurable or no? # The defualt from the shortcodes.py is '[%' and '%]'. app.parser = shortcodes.Parser(start='[chill', end=']', esc='\\') @app.template_filter('shortcodes') def shortcodes_filter(content): "Parse the rendered string for chill shortcodes" return Markup(app.parser.parse(content)) theme_static_folder = app.config.get('THEME_STATIC_FOLDER', None) if theme_static_folder: if theme_static_folder[0] != os.sep: theme_static_folder = os.path.join(os.getcwd(), theme_static_folder) app.config['THEME_STATIC_FOLDER'] = theme_static_folder theme_static_path = app.config.get('THEME_STATIC_PATH', '/theme/') if os.path.isdir( theme_static_folder ) and theme_static_path[0] == '/': app.add_url_rule('%s<path:filename>' % theme_static_path, view_func=app.send_theme_file) page.add_url_rule('/', view_func=PageView.as_view('page')) page.add_url_rule('/index.html', view_func=PageView.as_view('index')) page.add_url_rule('/<path:uri>/', view_func=PageView.as_view('page_uri')) page.add_url_rule('/<path:uri>/index.html', view_func=PageView.as_view('uri_index')) app.register_blueprint(page, url_prefix=app.config.get('PUBLIC_URL_PREFIX', '')) return app
def create_app(): app = Flask(__name__, static_folder="dist", static_url_path="") if os.environ.get('FLASK_ENV') in ['production', 'staging']: createMiddleWare(app, StackdriverExporter()) import googlecloudprofiler # Profiler initialization. It starts a daemon thread which continuously # collects and uploads profiles. Best done as early as possible. try: # service and service_version can be automatically inferred when # running on App Engine. googlecloudprofiler.start(verbose=3) except (ValueError, NotImplementedError) as exc: logging.error(exc) # Setup flask config if os.environ.get('FLASK_ENV') == 'test': cfg = import_string('configmodule.TestConfig')() elif os.environ.get('FLASK_ENV') == 'production': cfg = import_string('configmodule.ProductionConfig')() elif os.environ.get('FLASK_ENV') == 'webdriver': cfg = import_string('configmodule.WebdriverConfig')() elif os.environ.get('FLASK_ENV') == 'staging': cfg = import_string('configmodule.StagingConfig')() elif os.environ.get('FLASK_ENV') == 'development': cfg = import_string('configmodule.DevelopmentConfig')() else: raise ValueError("No valid FLASK_ENV is specified: %s" % os.environ.get('FLASK_ENV')) app.config.from_object(cfg) # Init extentions from cache import cache cache.init_app(app) # apply the blueprints to the app from routes import (browser, dev, factcheck, place, placelist, ranking, redirects, static, tools) app.register_blueprint(browser.bp) app.register_blueprint(dev.bp) app.register_blueprint(ranking.bp) app.register_blueprint(redirects.bp) app.register_blueprint(place.bp) app.register_blueprint(placelist.bp) app.register_blueprint(tools.bp) from routes.api import (chart, choropleth, place as place_api, landing_page, ranking as ranking_api, stats) app.register_blueprint(chart.bp) app.register_blueprint(choropleth.bp) app.register_blueprint(factcheck.bp) app.register_blueprint(place_api.bp) app.register_blueprint(landing_page.bp) app.register_blueprint(ranking_api.bp) app.register_blueprint(static.bp) app.register_blueprint(stats.bp) # Load chart config with open('chart_config.json') as f: chart_config = json.load(f) app.config['CHART_CONFIG'] = chart_config if cfg.WEBDRIVER or cfg.DEVELOPMENT: secret_client = secretmanager.SecretManagerServiceClient() secret_name = secret_client.secret_version_path(cfg.PROJECT, 'maps-api-key', '1') secret_response = secret_client.access_secret_version(secret_name) app.config['MAPS_API_KEY'] = secret_response.payload.data.decode( 'UTF-8') else: app.config['MAPS_API_KEY'] = "AIzaSyCi3WDvStkhQOBQRnV_4Fcuar7ZRteHgvU" if cfg.TEST or cfg.WEBDRIVER: app.config['PLACEID2DCID'] = { "ChIJCzYy5IS16lQRQrfeQ5K5Oxw": "country/USA", "ChIJPV4oX_65j4ARVW8IJ6IJUYs": "geoId/06" } else: # Load placeid2dcid mapping from GCS storage_client = storage.Client() bucket = storage_client.get_bucket(app.config['GCS_BUCKET']) blob = bucket.get_blob('placeid2dcid.json') app.config['PLACEID2DCID'] = json.loads(blob.download_as_string()) return app
config = { "dev": "config.DevConfig", "test": "config.TestConfig", "alpha": "config.AlphaConfig", "real": "config.RealConfig", } config_name = os.getenv('FLASK_CONFIGURATION', 'dev') app.config.from_object(config[config_name]) logging.info("PHASE : {}".format(config_name)) # Load the configuration from the instance folder if app.config.from_pyfile('config.py', silent=True): logging.info("Successfully read private configuration instance file.") cache.init_app(app) moment.init_app(app) @app.errorhandler(404) def not_found(error): return render_template('error/404.html'), 404 # Bllueprints logging.debug("Initializing Blueprints...") app.register_blueprint(main) app.register_blueprint(monitoring) app.register_blueprint(apis)
def create_app(): app = Flask(__name__, static_folder="dist", static_url_path="") if os.environ.get('FLASK_ENV') in ['production', 'staging', 'autopush']: createMiddleWare(app, StackdriverExporter()) import googlecloudprofiler # Profiler initialization. It starts a daemon thread which continuously # collects and uploads profiles. Best done as early as possible. try: # service and service_version can be automatically inferred when # running on GCP. googlecloudprofiler.start(verbose=3) except (ValueError, NotImplementedError) as exc: logging.error(exc) # Setup flask config cfg = libconfig.get_config() app.config.from_object(cfg) # Init extentions from cache import cache cache.init_app(app) # apply the blueprints to the app from routes import (protein, browser, dev, factcheck, place, placelist, ranking, redirects, static, tools) app.register_blueprint(protein.bp) app.register_blueprint(browser.bp) app.register_blueprint(dev.bp) app.register_blueprint(place.bp) app.register_blueprint(placelist.bp) app.register_blueprint(ranking.bp) app.register_blueprint(redirects.bp) app.register_blueprint(tools.bp) from routes.api import (protein as protein_api, browser as browser_api, choropleth, place as place_api, landing_page, ranking as ranking_api, stats, translator) app.register_blueprint(protein_api.bp) app.register_blueprint(browser_api.bp) app.register_blueprint(choropleth.bp) app.register_blueprint(factcheck.bp) app.register_blueprint(place_api.bp) app.register_blueprint(landing_page.bp) app.register_blueprint(ranking_api.bp) app.register_blueprint(static.bp) app.register_blueprint(stats.bp) app.register_blueprint(translator.bp) # Load chart config with open('chart_config.json', encoding='utf-8') as f: chart_config = json.load(f) app.config['CHART_CONFIG'] = chart_config if not cfg.TEST and not cfg.LITE: secret_client = secretmanager.SecretManagerServiceClient() secret_name = secret_client.secret_version_path(cfg.SECRET_PROJECT, 'maps-api-key', '1') secret_response = secret_client.access_secret_version(name=secret_name) app.config['MAPS_API_KEY'] = secret_response.payload.data.decode( 'UTF-8') if cfg.TEST or cfg.WEBDRIVER or cfg.LITE: app.config['PLACEID2DCID'] = { "ChIJCzYy5IS16lQRQrfeQ5K5Oxw": "country/USA", "ChIJPV4oX_65j4ARVW8IJ6IJUYs": "geoId/06" } else: # Load placeid2dcid mapping from GCS storage_client = storage.Client() bucket = storage_client.get_bucket(app.config['GCS_BUCKET']) blob = bucket.get_blob('placeid2dcid.json') app.config['PLACEID2DCID'] = json.loads(blob.download_as_bytes()) # Initialize translations babel = Babel(app, default_domain='all') app.config['BABEL_DEFAULT_LOCALE'] = i18n.DEFAULT_LOCALE app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n' if not cfg.TEST: timeout = 120 # seconds counter = 0 isOpen = False while not isOpen: try: urllib.request.urlopen(cfg.API_ROOT + "/version") break except urllib.error.URLError: time.sleep(1) counter += 1 if counter > timeout: raise RuntimeError("Mixer not ready after %s second" % timeout) @app.before_request def before_request(): requested_locale = request.args.get('hl', i18n.DEFAULT_LOCALE) g.locale_choices = i18n.locale_choices(requested_locale) g.locale = g.locale_choices[0] @babel.localeselector def get_locale(): return g.locale # Propagate hl parameter to all links (if not 'en') @app.url_defaults def add_language_code(endpoint, values): if 'hl' in values or g.locale == i18n.DEFAULT_LOCALE: return values['hl'] = g.locale # Provides locale parameter in all templates @app.context_processor def inject_locale(): return dict(locale=get_locale()) return app