def create_application(default_env='DEVELOPMENT'): """ Util method to create a fully configured `Flask app` for production/development/testing envs. We set all config'd objects as globals so they can be imported at the module level. """ from flask import Flask from flask_environments import Environments from flask.ext.mongoengine import MongoEngine from raven.contrib.flask import Sentry global application global env global db # Instatiate the app and the environment application = Flask(__name__) env = Environments(application, default_env=default_env) env.from_object('uber.config') # Instantiate the mongo connection db = MongoEngine(application) # Configure Sentry/error logging sentry = Sentry( application, dsn='https://*****:*****@app.getsentry.com/4404' ) # Import and route all views from uber.views import index return application
def create_app(app_config=None): app = Flask(__name__) # 读取配置文件 if app_config is None: env = Environments(app, var_name='env', default_env='None') env.from_object('app.config') else: app.config.from_object(configs[app_config]) # 蓝图注册 register_blueprints(app) # 扩展注册 register_extensions(app) # 自定义日期格式,待修改 datetime_format = app.config.get('APIZEN_DATETIME_FMT', '%Y/%m/%d %H:%M:%S') CustomJSONEncoder.datetime_format = datetime_format app.json_encoder = CustomJSONEncoder @app.route('/', methods=['GET']) def index(): return '<h1>请直接调用接口</h1>' return app
def make_env(app): # environment-based configuration loading env = Environments(app, var_name="BEAVY_ENV") env.from_yaml(os.path.join(BASE_DIR, 'config.yml')) # env.from_yaml(os.path.join(os.getcwd(), 'config.yml')) with open(os.path.join(os.getcwd(), 'config.yml'), "r") as r: deepmerge(app.config, yaml.load(r)) # allow for environment variables to update items if os.environ.get("BEAVY_CONFIG_FROM_ENV", False): app.config.update(os.environ) if "DATABASE_URL" in os.environ: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"] if "RABBITMQ_URL" in os.environ: app.config["CELERY_BROKER_URL"] = os.environ["RABBITMQ_URL"] if "REDIS_URL" in os.environ: app.config["RATELIMIT_STORAGE_URL"] = os.environ["REDIS_URL"] app.config["CACHE_REDIS_URL"] = os.environ["REDIS_URL"] # update social buttons _FLBLPRE = "flask_social_blueprint.providers.{}" if "SOCIAL_BLUEPRINT" not in app.config: app.config["SOCIAL_BLUEPRINT"] = dict([ ("." in name and name or _FLBLPRE.format(name), values) for name, values in app.config.get("SOCIAL_LOGINS").items()]) return env
def make_env(app): # environment-based configuration loading env = Environments(app, var_name="BEAVY_ENV") env.from_yaml(os.path.join(BASE_DIR, 'config.yml')) # env.from_yaml(os.path.join(os.getcwd(), 'config.yml')) with open(os.path.join(os.getcwd(), 'config.yml'), "r") as r: deepmerge(app.config, yaml.load(r)) # allow for environment variables to update items if os.environ.get("BEAVY_CONFIG_FROM_ENV", False): app.config.update(os.environ) if "DATABASE_URL" in os.environ: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"] if "RABBITMQ_URL" in os.environ: app.config["CELERY_BROKER_URL"] = os.environ["RABBITMQ_URL"] if "REDIS_URL" in os.environ: app.config["RATELIMIT_STORAGE_URL"] = os.environ["REDIS_URL"] app.config["CACHE_REDIS_URL"] = os.environ["REDIS_URL"] # update social buttons _FLBLPRE = "flask_social_blueprint.providers.{}" if "SOCIAL_BLUEPRINT" not in app.config: app.config["SOCIAL_BLUEPRINT"] = dict([ ("." in name and name or _FLBLPRE.format(name), values) for name, values in app.config.get("SOCIAL_LOGINS").items() ]) return env
def create_app(config_name): app = Flask(__name__) env = Environments(app, default_env=config_name) app.config.from_object(env.from_yaml('config.yml')) certfile = app.config['OAUTH_CERTIFICATE_PATH'] with open(certfile, 'r') as contents: key_contents = contents.read() key = RSA.importKey(key_contents) app.oauth_certificate = key.publickey().exportKey() bootstrap.init_app(app) db.init_app(app) mail.init_app(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify sslify = SSLify(app) @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') return app
def create_app(config_name): app = Flask(__name__) env = Environments(app, default_env=config_name) app.config.from_object(env.from_yaml('config.yml')) certfile = app.config['OAUTH_CERTIFICATE_PATH'] with open(certfile, 'r') as fd: kt = fd.read() key = RSA.importKey(kt) app.oauth_certificate = key.publickey().exportKey() bootstrap.init_app(app) db.init_app(app) mail.init_app(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify sslify = SSLify(app) @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') return app
def create_app(package_name, package_path, settings_override=None, settings='settings.yaml'): """ Create a L{flask.Flask} application with common configuration applied. @param package_name: application package name. @param package_path: package path to search for blueprints. @param settings: the settings per environment in YAML. @param settings_override: a dictionary of settings to override. @return: the Flask application; never C{None}. """ app = Flask(package_name, instance_relative_config=True) env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), '', settings)) app.config.from_object(settings_override) logging.basicConfig(level=logging.DEBUG) register_blueprints(app, package_name, package_path) return app
def create_app(config_name): app = Flask(__name__) env = Environments(app, default_env=config_name) env.from_yaml(os.path.join(basedir, 'config.yml')) celery.conf.update(BROKER_URL=app.config['REDIS_URL'], CELERY_RESULT_BACKEND=app.config['REDIS_URL']) #Adding logging capabilities. if app.config['LOGGING'] == True: import logging logger = logging.getLogger('replicate') logger.setLevel(logging.DEBUG) log_directory = basedir + app.config['LOG_FILE_PTAH'] log_filename = log_directory + app.config['LOG_FILE'] if not os.path.exists(os.path.dirname(log_filename)): os.makedirs(os.path.dirname(log_filename)) file_handler = logging.FileHandler(log_filename, mode='a+') stream_handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(process)d - %(name)s - %(module)s:%(lineno)d - %(levelname)s - %(message)s' ) file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) app.logger.addHandler(file_handler) #app.logger.addHandler(stream_handler) app.logger.setLevel(logging.DEBUG) app.logger.info('Application Process Started') #SSL if not app.debug and not app.testing and app.config['SSL_DISABLE']: from flask.ext.sslify import SSLify sslify = SSLify(app) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) db.init_app(app) login_manager.init_app(app) cache.init_app(app) csrf.init_app(app) redis_store.init_app(app) from ooiservices.app.main import api as main_blueprint app.register_blueprint(main_blueprint) from ooiservices.app.uframe import uframe as uframe_blueprint app.register_blueprint(uframe_blueprint, url_prefix='/uframe') from ooiservices.app.redmine import redmine as redmine_blueprint app.register_blueprint(redmine_blueprint, url_prefix='/redmine') return app
def create_app(): """Return a Flask app configured for the correct env (test, dev, prod).""" app = Flask(__name__) env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), 'config.yaml')) api = Api(app) api.add_resource(PlayerListResource, '/players') api.add_resource(PlayerResource, '/players/<string:name>') api.add_resource(GameListResource, '/games') api.add_resource(ChallengeListResource, '/challenges') db.init_app(app) return app
def make_env(app): # environment-based configuration loading env = Environments(app, var_name="BEAVY_ENV") env.from_yaml(os.path.join(BASE_DIR, 'config.yml')) # env.from_yaml(os.path.join(os.getcwd(), 'config.yml')) with open(os.path.join(os.getcwd(), 'config.yml'), "r") as r: deepmerge(app.config, yaml.load(r)) # update social buttons _FLBLPRE = "flask_social_blueprint.providers.{}" if "SOCIAL_BLUEPRINT" not in app.config: app.config["SOCIAL_BLUEPRINT"] = dict([ ("." in name and name or _FLBLPRE.format(name), values) for name, values in app.config.get("SOCIAL_LOGINS").items()]) return env
def make_env(app): # environment-based configuration loading env = Environments(app, var_name="BEAVY_ENV") env.from_yaml(os.path.join(BASE_DIR, 'config.yml')) # env.from_yaml(os.path.join(os.getcwd(), 'config.yml')) with open(os.path.join(os.getcwd(), 'config.yml'), "r") as r: deepmerge(app.config, yaml.load(r)) # update social buttons _FLBLPRE = "flask_social_blueprint.providers.{}" if "SOCIAL_BLUEPRINT" not in app.config: app.config["SOCIAL_BLUEPRINT"] = dict([ ("." in name and name or _FLBLPRE.format(name), values) for name, values in app.config.get("SOCIAL_LOGINS").items() ]) return env
def __init__(self): super(Main, self).__init__( __name__, static_url_path='/res', static_folder='../webapp/resources', template_folder='templates') # Runtime environment (e.g., export FLASK_ENV=PRODUCTION) # https://pythonhosted.org/Flask-Environments env = Environments(self) env.from_yaml(os.path.join(os.getcwd(), 'config/config.yml')) # Config logging. # https://docs.python.org/2/howto/logging.html logging.config.dictConfig(yaml.load(open(self.config['LOG_CONFIG']))) # Jinja2 templates. # http://jinja.pocoo.org/docs/dev/api # http://flask.pocoo.org/docs/0.10/api/#flask.Flask.jinja_options self.jinja_options = flask.Flask.jinja_options.copy() self.jinja_options.update(dict( trim_blocks=True, lstrip_blocks=True )) # http://pythonhosted.org/Flask-Session # http://flask.pocoo.org/docs/0.10/quickstart/#sessions self.session = Session(self) # Enable injection within this class. # https://github.com/alecthomas/injector injector = Injector() injector.install_into(self) # Flask injection. # NOTE: Order of modules is important. LOG.info('### %s ###' % self.config['ENVIORNMENT']) FlaskInjector(app=self, injector=injector, modules=[ ConfigModule, OAuthConfigModule, TwitterModule, ViewModule, OAuthRouterModule ])
def create_app(environment="DEVELOPMENT"): """worldofsfx application factory. This function defines a re-usable pattern for instantiating and creating application objects. :param str environment: Specify the name of the configuration object used to build this application object Usage:: from worldofsfx import create_app from unittest import TestCase class MyTest(TestCase): def setUp(self): self.app = create_app(environment="TESTING") :returns: flask application :rtype: :obj:`flask.Flask` """ if not environment: env_name = "DEVELOPMENT" else: env_name = environment.upper() app = Flask(__name__) env = Environments(app, default_env=env_name) env.from_object("worldofsfx.config") wos_privates = os.getenv("WOS_PRIVATES") if wos_privates: env.from_object(wos_privates) app.template_folder = app.config.get("TEMPLATE_FOLDER", "templates") app.register_blueprint(wos) app.register_blueprint(events) app.register_blueprint(buzz) app.register_blueprint(beatport) db.init_app(app) return app
class FlaskEnvironmentsTestCase(unittest.TestCase): DEFAULT_ENV = None VAR_NAME = None DATABASE_VALUE = 'development_db' def setUp(self): self.app = Flask(__name__) self.environments = Environments(self.app, var_name=self.VAR_NAME, default_env=self.DEFAULT_ENV) def test_from_object(self): self.environments.from_object('tests.config') self.assertEqual(self.app.config['DATABASE'], self.DATABASE_VALUE) def test_from_yaml(self): path = os.path.join(os.getcwd(), 'tests', 'config.yml') self.environments.from_yaml(path) self.assertEqual(self.app.config['DATABASE'], self.DATABASE_VALUE)
def create_app(): """ This method create the Flask application. :return: Flask App Object """ global app global login app = Flask(__name__, instance_relative_config=True) flask_env = os.getenv('FLASK_ENV', 'None') if flask_env == 'development': config_object = 'config.DevConfig' elif flask_env == 'testing': config_object = 'config.TestConfig' elif flask_env == 'production': config_object = 'config.ProdConfig' else: raise RuntimeError( "%s is not recognized as valid app environment. You have to setup the environment!" % flask_env) # Load config env = Environments(app) env.from_object(config_object) # Configuring redis create_redis(app) register_extensions(app) register_blueprints(app) register_handlers(app) # loading login manager import gooutsafe.auth.login_manager as lm login = lm.init_login_manager(app) if flask_env == 'testing' or flask_env == 'development': register_test_blueprints(app) return app
def create_app(package_name, package_path, settings_override=None, settings='settings.yaml'): """ Create a L{flask.Flask} application with common configuration applied. @param package_name: application package name. @param settings_override: a dictionary of settings to override. @return: the Flask application; never C{None}. """ app = Flask(package_name, instance_relative_config=True) env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), '', settings)) app.config.from_object(settings_override) logging.basicConfig(level=logging.DEBUG) register_blueprints(app, package_name, package_path) register_injection_modules(app, package_name, package_path, settings_override=settings_override) return app
def create_app_api(): app = Flask(SERVICE_NAME) config_env = Environments(app, default_env="DEVELOPMENT") config_env.from_object('config') config_redis_ipport = app.config["CONFIG_REDIS_IPPORT"] config_redis_password = app.config["CONFIG_REDIS_PWD"] app.config[ 'REDIS_URL'] = "redis://:" + config_redis_password + "@" + config_redis_ipport + "/7" redisService.init_app(app) api_plus = Api(app, version="v1.0.0", title=SERVICE_NAME, prefix=APP_URL_PREFIX) # 首先打开(或创建)一个scheduler.lock文件,并加上非阻塞互斥锁。成功后创建scheduler并启动。 f = open("scheduler.lock", "wb") try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) scheduler = APScheduler() scheduler.init_app(app) scheduler.start() except: # 如果加文件锁失败,说明scheduler已经创建,就略过创建scheduler的部分。 pass # 最后注册一个退出事件,如果这个flask项目退出,则解锁并关闭scheduler.lock文件的锁。 def unlock(): fcntl.flock(f, fcntl.LOCK_UN) f.close() atexit.register(unlock) BASIC_URL_PREFIX = "/basic" # stellar基础接口(用户、区块浏览器等相关) api_plus.add_namespace(basic_ns, BASIC_URL_PREFIX) return app, api_plus
Application and project global declarations Copyright 2015 RPS ASA See LICENSE.txt ''' from flask import Flask from flask_environments import Environments from flask.ext.sqlalchemy import SQLAlchemy from flask_restful import Api from cbibs_api.reverse_proxy import ReverseProxied import os app = Flask(__name__) app.wsgi_app = ReverseProxied(app.wsgi_app) env = Environments(app) env.from_yaml('config.yml') if os.path.exists('config.local.yml'): env.from_yaml('config.local.yml') if app.config['LOGGING'] == True: import logging logger = logging.getLogger('pyprojects.app') logger.setLevel(logging.DEBUG) log_directory = app.config['LOG_FILE_PATH'] log_filename = os.path.join(log_directory,app.config['LOG_FILE']) if not os.path.exists(os.path.dirname(log_filename)): os.makedirs(os.path.dirname(log_filename)) file_handler = logging.FileHandler(log_filename, mode='a+')
import logging from logging.handlers import RotatingFileHandler from celery import Celery from flask import Flask from flask_environments import Environments from flask_mongoengine import MongoEngine from celery.signals import before_task_publish, task_prerun, task_success, task_failure import mongoengine from datetime import datetime import pytz from config import celery_config from db.mongo_models import task_monitor app = Flask(__name__) env = Environments(app) env.from_object('config.flask_config') basedir = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir)) # os.path.abspath(os.path.dirname(__file__)) file_handler = RotatingFileHandler(basedir + "/logs/logger_flask.log", encoding='utf-8') formatter = logging.Formatter("%(asctime)s\t%(levelname)s\t%(message)s") file_handler.setFormatter(formatter) # 初始化mongodb monogo_conn = MongoEngine() monogo_conn.init_app(app) flask_celery = Celery(app.name, broker=celery_config.CELERY_BROKER_URL)
from flask_environments import Environments from flask_injector import FlaskInjector import os from config import ConfigModule from view import ViewModule import service.twitter # # Flask App. # app = flask.Flask(__name__, template_folder='templates') # Runtime environment (FLASK_ENV) # https://pythonhosted.org/Flask-Environments env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), 'config/config.yml')) # Flask injection modules. # https://github.com/alecthomas/injector FlaskInjector(app=app, modules=[ ConfigModule, ViewModule, service.twitter.ServiceModule ]) # # Start-up. # if __name__ == '__main__': app.run(host='0.0.0.0', port=app.config['PORT'])
#!/usr/bin/env python ''' ooiui.core.app.science Defines the application for the Science UI ''' import os from flask import Flask from flask.ext.cache import Cache from flask_environments import Environments app = Flask(__name__, static_url_path='', template_folder='../../templates', static_folder='../../static') env = Environments(app, default_env='DEVELOPMENT') basedir = 'ooiui/config' if os.path.exists(os.path.join(basedir, 'config_local.yml')): env.from_yaml(os.path.join(basedir, 'config_local.yml')) else: env.from_yaml(os.path.join(basedir, 'config.yml')) cache = Cache(app, config={'CACHE_TYPE': app.config['CACHE_TYPE']})
from flask import Flask from flask.ext.assets import Environment, Bundle from flask_environments import Environments from flask.ext.sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap import os # Create app GisApp = Flask(__name__) Bootstrap(GisApp) # GisApp.config.from_object('config') db = SQLAlchemy(GisApp) env = Environments(GisApp) env.from_object('config') # Assets assets = Environment(GisApp) js = Bundle('javascripts/leaflet-src.js', 'javascripts/main.js', 'javascripts/leaflet.markercluster-src.js','javascripts/leaflet.draw-src.js', 'javascripts/handlebars-v3.0.3.js', 'javascripts/Control.Geocoder.js', 'javascripts/underscore-min.js', filters='jsmin', output='gen/packed.js') admin_js = Bundle('javascripts/leaflet-src.js', 'javascripts/jquery-2.1.3.min.js', 'javascripts/admin_main.js', 'javascripts/leaflet.draw-src.js', filters='jsmin', output='gen/admin_packed.js') assets.register('application_js', js) assets.register('admin_application_js', admin_js) less = Bundle('stylesheets/leaflet.css', 'stylesheets/main.less.css', 'stylesheets/MarkerCluster.css', 'stylesheets/MarkerCluster.Default.css','stylesheets/leaflet.draw.css', 'stylesheets/Control.Geocoder.css', filters='less,cssmin', output='gen/packed.css') admin_less = Bundle('stylesheets/leaflet.css', 'stylesheets/admin_main.less.css','stylesheets/leaflet.draw.css', filters='less,cssmin', output='gen/admin_packed.css')
from flask import Flask from frontend.app import frontend_bp from backend.persistencia import Persistencia from flask_environments import Environments from b_logic.business import Billetera billetera = Billetera() persistencia = Persistencia('190.188.234.6', 'admin', 'admin2k14') app = Flask(__name__) env = Environments(app) env.from_object('billetera') app.register_blueprint(frontend_bp, url_prefix="/frontend") #app.register_blueprint(backoffice_bp, url_prefix="/backoffice") app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' if __name__ == '__main__': app.config['TRAP_BAD_REQUEST_ERRORS'] = True app.run(debug=True)
# Licensed under MIT # Version 1.0.0-alpha6 import os import sys from flask import Flask, jsonify from flask_environments import Environments from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_caching import Cache from flask_cors import cross_origin from oauth2client.service_account import ServiceAccountCredentials # instantiate the application app = Flask(__name__) env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), 'conf/main.yml')) db = SQLAlchemy(app) ma = Marshmallow(app) # setup caching cache = Cache(app, config={ 'CACHE_TYPE': app.config['CACHE']['TYPE'], 'CACHE_DIR': os.path.join(os.getcwd(), app.config['CACHE']['DIRECTORY']) }) @app.errorhandler(404)
from flask import Flask, render_template from flask_environments import Environments app = Flask(__name__) # Recuperation des données de paramétrages de l'application # Shell variable creation : $ export FLASK_ENV="DevelopmentConfig" # TODO : [MODERNISATION] utilisation d'un fichier YAML env = Environments(app, var_name='FLASK_ENV', default_env='TestConfig') env.from_object('config') from app.utils import logmanager
#!/usr/bin/env python ''' ooiui.core.app.science Defines the application for the Science UI ''' from flask import Flask from flask.ext.cache import Cache from flask_environments import Environments app = Flask(__name__, static_url_path='', template_folder='../../templates', static_folder='../../static') env = Environments(app, default_env='DEVELOPMENT') env.from_yaml('ooiui/config/config.yml') cache = Cache(app, config={'CACHE_TYPE': app.config['CACHE_TYPE']})
def setUp(self): self.app = Flask(__name__) self.environments = Environments(self.app, var_name=self.VAR_NAME, default_env=self.DEFAULT_ENV)
from flaskext.csrf import csrf import os, sys import helpers import config from models import db from Mailer import MailerController ### Set up the Flask application application = Flask(__name__) env = Environments(application) # Load the appropriate configuration depending on # the current environment. Development is for local # testing, and production is for AWS. if os.environ.get('FLASK_ENV') == 'Development': env.from_object(config.Development) # If we're in development mode, we need to load SQLite # and enable foreign keys on it (to support relations # in our models). from sqlalchemy import event from sqlalchemy.engine import Engine from sqlite3 import Connection as SQLite3Connection @event.listens_for(Engine, "connect") def _set_sqlite_pragma(dbapi_connection, connection_record):
def create_app(config_name): app = Flask(__name__) env = Environments(app, default_env=config_name) if os.path.exists(os.path.join(basedir, 'config_local.yml')): env.from_yaml(os.path.join(basedir, 'config_local.yml')) else: env.from_yaml(os.path.join(basedir, 'config.yml')) celery.conf.update(BROKER_URL=app.config['REDIS_URL'], CELERY_RESULT_BACKEND=app.config['REDIS_URL']) #Adding logging capabilities. if app.config['LOGGING'] == True: import logging logger = logging.getLogger('replicate') logger.setLevel(logging.DEBUG) log_directory = basedir + app.config['LOG_FILE_PTAH'] log_filename = log_directory + app.config['LOG_FILE'] if not os.path.exists(os.path.dirname(log_filename)): os.makedirs(os.path.dirname(log_filename)) file_handler = logging.FileHandler(log_filename, mode='a+') stream_handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(process)d - %(name)s - %(module)s:%(lineno)d - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) app.logger.addHandler(file_handler) #app.logger.addHandler(stream_handler) app.logger.setLevel(logging.DEBUG) app.logger.info('Application Process Started') #SSL if not app.debug and not app.testing and app.config['SSL_DISABLE']: from flask.ext.sslify import SSLify sslify = SSLify(app) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) db.init_app(app) login_manager.init_app(app) cache.init_app(app) csrf.init_app(app) redis_store.init_app(app) cors.init_app(app) from ooiservices.app.main import api as main_blueprint app.register_blueprint(main_blueprint) from ooiservices.app.uframe import uframe as uframe_blueprint app.register_blueprint(uframe_blueprint, url_prefix='/uframe') from ooiservices.app.redmine import redmine as redmine_blueprint app.register_blueprint(redmine_blueprint, url_prefix='/redmine') # If debug is enabled add route for site-map if app.config['DEBUG']: app.add_url_rule('/site-map', 'site_map', site_map) return app
def create_app(broker_start=False, log_level=logging.ERROR): """ This method create the Flask application. :return: Flask App Object """ global db global app global migrate global login api_app = connexion.App(__name__, server='flask', specification_dir='openapi/') # getting the flask app app = api_app.app flask_env = os.getenv('FLASK_ENV', 'None') if flask_env == 'development': config_object = 'config.DevConfig' elif flask_env == 'testing': config_object = 'config.TestConfig' elif flask_env == 'production': config_object = 'config.ProdConfig' else: raise RuntimeError( "%s is not recognized as valid app environment. You have to setup the environment!" % flask_env) # Load config env = Environments(app) env.from_object(config_object) # configuring logging logging.basicConfig(level=log_level) # loading communications import gooutsafe.comm as comm if broker_start: if flask_env != 'testing': comm.init_rabbit_mq(app) else: comm.disabled = True # registering db db = SQLAlchemy(app=app) # importing models try: import gooutsafe.models.reservation except ImportError: raise RuntimeError('Cannot import the models!') # creating migrate migrate = Migrate(app=app, db=db) # checking the environment if flask_env == 'testing': # we need to populate the db db.create_all() # registering to api app all specifications register_specifications(api_app) return app
import os from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy from flask_environments import Environments from flask.ext.bootstrap import Bootstrap from jinja2 import Environment, PackageLoader # init flask app app = Flask(__name__) # init db con db = SQLAlchemy(app) # configure flask env = Environments(app) env.from_yaml(os.path.join(os.getcwd(), 'flaskapi', 'config', 'config.yml')) # configure jinja env = Environment(loader=PackageLoader('flaskapi', 'templates')) env.filters['jsonify'] = jsonify # bootstrap bootstrap = Bootstrap(app) # TODO: configure per environment logging # app module imports import models.asset import controllers.api import controllers.errors
# coding=utf-8 import logging as log from flask import Flask, request, send_from_directory from flask_restful import Api from flask_environments import Environments from common.exceptions import HoneybeeException from util import restful_tools as rest app = Flask(__name__) # FLASK_ENV变量控制honeybee对环境变量的选择,默认为DEVELOPMENT # os.environ['FLASK_ENV'] = 'PRODUCTION' env = Environments(app) env.from_object('conf.config') api = Api(app) @app.errorhandler(Exception) def handle_error(e): """ 全局异常拦截 :param e: 被截获的异常 :return: 接口抛出异常后直接将这个异常返回 """ code = 500 if isinstance(e, HoneybeeException): code = e.code log.error(e, exc_info=1) return rest.responseto(None, message=e.message, code=code, success=False)
# import sys # print(os.path.dirname(__file__)) # print(os.path.dirname(os.path.abspath(__file__))) # sys.path.append(os.path.dirname(__file__)) # sys.path.append(os.path.dirname(os.path.abspath(__file__))) # print(sys.path) from app import init_beas_when_app_start from app.soda_log import init_log from app.visualization.soda_visualization_api import base_ns from app.common.soda_common import SDCommonJsonRet, SDResource, SDCodeMsg, SDRequestParser from app import sodaVisualizationService SERVICE_NAME = "soda_potentialpie_pyservice" APP_URL_PREFIX = "/v1/api/soda" app = Flask(SERVICE_NAME) config_env = Environments(app,default_env="DEVELOPMENT") config_env.from_object('config') # 日志 init_log() #加载配置 生产对应环境(生产/开发)的bean init_beas_when_app_start(app) api_plus = Api(app,version="v1.0.0",title=SERVICE_NAME,prefix=APP_URL_PREFIX) #基础接口 BASE_URL_PREFIX = "/base"
sys.exit(1) dataset_gen_src = '' for line in sys.stdin: dataset_gen_src += line if len(dataset_gen_src) == 0: print >> sys.stderr, "Empty dataset generator!" sys.exit(1) user_id = int(sys.argv[1]) campaign_id = int(sys.argv[2]) ### Set up our flask environment so we can access the DB application = Flask(__name__) env = Environments(application) if os.environ.get('FLASK_ENV') == 'Development': env.from_object(config.Development) elif os.environ.get('FLASK_ENV') == 'Production': env.from_object(config.Production) else: env.from_object(config.Production) ### Setup DB db.app = application db.init_app(application) db.create_all() ### Read in our harness code with application.open_resource('static/js/dataset-generator-harness.js') as harness_file:
from flask import Flask from flask_environments import Environments from weibo import Client app = Flask(__name__) env = Environments(app) env.from_object('config-devel') print app.config weiboClient = Client(app.config['WEIBO_API_KEY'], app.config['WEIBO_API_SECRET'], app.config['WEIBO_API_REDIRECT_URI'])
from flask_environments import Environments from flask_migrate import Migrate from api.blueprints import register_blueprints as register_api_blueprints from auth.auth import register_login_logout from auth.blueprints import register_blueprints as register_auth_blueprints from common.errors import init_error_handlers from common.resources import Api from common.schemas import marshmallow from database import models # noqa ## so alembic is aware of all the models from database import db from database.db import setup_pg_extensions api = Api() cors = CORS(resources={r"/*": {"origins": "*"}}) env = Environments() migrate = Migrate(compare_type=True) oauth = OAuth() def init_plugins(app): """Initialise plugins that need to run BEFORE app context is activated Args: app: flask app with no activated context """ from database import models # noqa env.init_app(app) api.init_app(app) marshmallow.init_app(app) cors.init_app(app)
# Copyright 2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from flask import Flask from flask_environments import Environments from pymongo import MongoClient app = Flask(__name__) env = Environments(app) env.from_yaml( os.path.join( os.path.abspath(os.path.join('..', os.path.dirname(__file__))), '..', 'config.yaml')) mongodb = MongoClient(app.config['MONGO_HOST'], app.config['MONGO_PORT']) db = mongodb[app.config['MONGO_DBNAME']]
import os import datetime import json import re from functools import wraps from flask import Flask, redirect, request, current_app __version__ = "3.2.2" # Create application object app = Flask(__name__) from flask_environments import Environments env = Environments(app) env.from_yaml('config.yml') if os.path.exists('config.local.yml'): env.from_yaml('config.local.yml') app.config.from_object('ioos_catalog.defaults') import sys # Setup RQ Dashboard from rq_dashboard import RQDashboard RQDashboard(app) # Create logging if app.config.get('LOG_FILE') == True: import logging from logging import FileHandler
def create_app(): """ This method create the Flask application. :return: Flask App Object """ global db global app global migrate global login global celery app = Flask(__name__, instance_relative_config=True) flask_env = os.getenv('FLASK_ENV', 'None') if flask_env == 'development': config_object = 'config.DevConfig' elif flask_env == 'testing': config_object = 'config.TestConfig' elif flask_env == 'production': config_object = 'config.ProdConfig' else: raise RuntimeError( "%s is not recognized as valid app environment. You have to setup the environment!" % flask_env) # Load config env = Environments(app) env.from_object(config_object) # registering db db = SQLAlchemy( app=app ) # creating celery celery = make_celery(app) # requiring the list of models register_extensions(app) register_blueprints(app) register_handlers(app) # loading login manager import gooutsafe.auth as auth login = auth.init_login_manager(app) # creating migrate migrate = Migrate( app=app, db=db ) # checking the environment if flask_env == 'testing': # we need to populate the db db.create_all() if flask_env == 'testing' or flask_env == 'development': register_test_blueprints(app) return app
''' app The application context ''' from celery import Celery from celery.schedules import crontab from flask import Flask, url_for, jsonify from flask_environments import Environments import os celery = Celery('__main__') app = Flask(__name__, static_folder='web/static') env = Environments(app, default_env='DEVELOPMENT') env.from_yaml('config.yml') # Override config file with local version if os.path.exists('config.local.yml'): env.from_yaml('config.local.yml') celery.conf.update(broker_url=app.config['REDIS_URL'], result_backend=app.config['REDIS_URL']) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs):
def create_app(): """ This method create the Flask application. :return: Flask App Object """ global db global app global migrate global api_app # first initialize the logger init_logger() api_app = connexion.FlaskApp( __name__, server='flask', specification_dir='openapi/', ) # getting the flask app app = api_app.app flask_env = os.getenv('FLASK_ENV', 'None') if flask_env == 'development': config_object = 'config.DevConfig' elif flask_env == 'testing': config_object = 'config.TestConfig' elif flask_env == 'production': config_object = 'config.ProdConfig' else: raise RuntimeError( "%s is not recognized as valid app environment. You have to setup the environment!" % flask_env) # Load config env = Environments(app) env.from_object(config_object) # creating redis instance create_redis(app) # loading communications import gooutsafe.comm as comm if flask_env != 'production': # disable communication for testing purposes comm.disabled = True else: comm.init_rabbit_mq(app) # registering db db = SQLAlchemy( app=app ) # requiring the list of models import gooutsafe.models # creating migrate migrate = Migrate( app=app, db=db ) # checking the environment if flask_env == 'testing': # we need to populate the db db.create_all() # registering to api app all specifications register_specifications(api_app) return app
def create_app(config_name): app = Flask(__name__) env = Environments(app, default_env=config_name) if os.path.exists(os.path.join(basedir, "config_local.yml")): env.from_yaml(os.path.join(basedir, "config_local.yml")) else: env.from_yaml(os.path.join(basedir, "config.yml")) # Uses REDIS_URL from config.yml to set the connection to the redis-server cache.config = {"CACHE_TYPE": "redis", "CACHE_REDIS_URL": app.config["REDIS_URL"]} # Adding logging capabilities. if app.config["LOGGING"] is True: import logging logger = logging.getLogger("replicate") logger.setLevel(logging.DEBUG) log_directory = basedir + app.config["LOG_FILE_PTAH"] log_filename = log_directory + app.config["LOG_FILE"] if not os.path.exists(os.path.dirname(log_filename)): os.makedirs(os.path.dirname(log_filename)) file_handler = logging.FileHandler(log_filename, mode="a+") stream_handler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s - %(process)d - %(name)s - " + "%(module)s:%(lineno)d - %(levelname)s - %(message)s" ) file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # app.logger.addHandler(stream_handler) app.logger.setLevel(logging.DEBUG) app.logger.info("Application Process Started") # SSL if not app.debug and not app.testing and app.config["SSL_DISABLE"]: from flask.ext.sslify import SSLify sslify = SSLify(app) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) db.init_app(app) login_manager.init_app(app) cache.init_app(app) csrf.init_app(app) redis_store.init_app(app) cors.init_app(app) # Flask-Security Init from ooiservices.app.models import User, Role user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) from ooiservices.app.main import api as main_blueprint app.register_blueprint(main_blueprint) from ooiservices.app.uframe import uframe as uframe_blueprint app.register_blueprint(uframe_blueprint, url_prefix="/uframe") from ooiservices.app.redmine import redmine as redmine_blueprint app.register_blueprint(redmine_blueprint, url_prefix="/redmine") from ooiservices.app.alfresco import alfresco as alfresco_blueprint app.register_blueprint(alfresco_blueprint, url_prefix="/alfresco") from ooiservices.app.m2m import m2m as m2m_blueprint app.register_blueprint(m2m_blueprint, url_prefix="/m2m") # If debug is enabled add route for site-map if app.config["DEBUG"]: app.add_url_rule("/site-map", "site_map", site_map) return app
# Copyright 2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from flask import Flask from flask_environments import Environments from pymongo import MongoClient app = Flask(__name__) env = Environments(app) env.from_yaml(os.path.join(os.path.abspath(os.path.join('..', os.path.dirname(__file__))), '..', 'config.yaml')) mongodb = MongoClient(app.config['MONGO_HOST'], app.config['MONGO_PORT']) db = mongodb[app.config['MONGO_DBNAME']]
from flask_environments import Environments from app.css_assets import non_admin_css_files, admin_css_files, gallery_css_files from app.js_assets import non_admin_js_files, admin_js_files, gallery_js_files # Create app GisApp = Flask(__name__) Bootstrap(GisApp) # for using jQuery 2 from cdn instead of jQuery 1 # (https://github.com/mbr/flask-bootstrap/blob/master/docs/faq.rst#how-can-i-use-jquery2-instead-of-jquery1) GisApp.extensions['bootstrap']['cdns']['jquery'] = WebCDN( '//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/') # GisApp.config.from_object('config') db = SQLAlchemy(GisApp) env = Environments(GisApp) env.from_object('config') # Assets assets = Environment(GisApp) js = Bundle(*non_admin_js_files, filters='jsmin', output='gen/packed.js') admin_js = Bundle(*admin_js_files, filters='jsmin', output='gen/admin_packed.js') gallery_js = Bundle(*gallery_js_files, filters='jsmin', output='gen/gallery_packed.js') assets.register('application_js', js) assets.register('admin_application_js', admin_js)
import osmapi from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from flask_environments import Environments # Create app GisGeneratorApp = Flask(__name__) Bootstrap(GisGeneratorApp) # GisApp.config.from_object('config') db = SQLAlchemy(GisGeneratorApp) env = Environments(GisGeneratorApp) env.from_object('config') # Load Routes from app import routes # configure OSM Api GisGeneratorApp.osmApiClient = osmapi.OsmApi( api=GisGeneratorApp.config['OSMAPI_CONFIG']['domain'], username=GisGeneratorApp.config['OSMAPI_CONFIG']['username'], password=GisGeneratorApp.config['OSMAPI_CONFIG']['password'] )
def create_app(): """ This method create the Flask application. :return: Flask App Object """ global db global app global api_app global celery # first initialize the logger init_logger() api_app = connexion.FlaskApp( __name__, server='flask' ) # getting the flask app app = api_app.app flask_env = os.getenv('FLASK_ENV', 'None') if flask_env == 'development': config_object = 'config.DevConfig' elif flask_env == 'testing': config_object = 'config.TestConfig' elif flask_env == 'production': config_object = 'config.ProdConfig' else: raise RuntimeError( "%s is not recognized as valid app environment. You have to setup the environment!" % flask_env) # Load config env = Environments(app) env.from_object(config_object) # creating celery celery = make_celery(app) # loading communications import gooutsafe.comm as comm #if flask_env != 'testing': comm.init_rabbit_mq() """else: comm.disabled = True""" if flask_env != 'production': # disable communication for testing purposes comm.disabled = True else: comm.init_rabbit_mq() db = MongoEngine( app=app ) # requiring the list of models import gooutsafe.models # registering to api app all specifications register_specifications(api_app) return app
__init__.py ~~~~~~~~~~~ """ import os, os.path as op from flask import Flask from flask.ext import admin from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import Security, SQLAlchemyUserDatastore from flask_environments import Environments import flask_admin app = Flask(__name__) env = Environments(app) ROOT = os.path.dirname(__file__) CONFIG_YAML = 'config.yaml' if os.path.exists(op.join(ROOT, 'config.yaml')): env.from_yaml(op.join(ROOT, 'config.yaml')) if hasattr(app.config, 'DEBUG_TOOLBAR') and app.config['DEBUG_TOOLBAR']: from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension(app) db = SQLAlchemy(app) # Custom login.
from flask import Flask from flask.ext.mongokit import MongoKit from flask.ext.login import LoginManager from flask.ext.mail import Mail from flask_environments import Environments # Create application object app = Flask(__name__) env = Environments(app) env.from_yaml('config.yml') # Create logging if app.config.get('LOG_FILE') == True: import logging from logging import FileHandler file_handler = FileHandler('log.txt') file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) # Create the database connection db = MongoKit(app) # Create the Redis connection import redis from rq import Queue redis_connection = redis.from_url(app.config.get("REDIS_URL")) queue = Queue('default', connection=redis_connection, default_timeout=600) from rq_scheduler import Scheduler scheduler = Scheduler(queue_name="default", connection=redis_connection)
from flask.ext import login from flask.ext.admin.base import MenuLink, Admin, BaseView, expose from flask.ext.admin.contrib import sqla from wtforms import PasswordField import os from collections import OrderedDict from datetime import datetime from redis import Redis from flask.ext.admin.contrib import rediscli # Create app app = Flask(__name__) # Import the config.yml or config_local.yml file and load it into the app environment basedir = os.path.abspath(os.path.dirname(__file__)) env = Environments(app, default_env='PRODUCTION') if os.path.exists(os.path.join(basedir, 'config_local.yml')): env.from_yaml(os.path.join(basedir, 'config_local.yml')) else: env.from_yaml(os.path.join(basedir, 'config.yml')) # Setup mail functionality mail = Mail(app) # Create database connection object db = SQLAlchemy(app) # These classes are from ooi-ui-services, slightly modified # TODO: Figure out a way to keep these classes maintained with ooi-ui-services
""" Mail reader and pase images linkg generate database and download images """ import os from flask import Flask from flask.ext.cors import CORS from flask_environments import Environments from flask.ext.pymongo import PyMongo app = Flask(__name__) app.name = 'Mailer' env = Environments(app) config_file = os.path.join(os.path.abspath('./app'), 'config', 'config.yml') secrets_file = os.path.join(os.path.abspath('./app'), 'config', 'secrets.yml') env.from_yaml(config_file) env.from_yaml(secrets_file) mongo = PyMongo(app) CORS(app) app.jinja_env.line_statement_prefix = '%' from app import routers
def create_index(self, name): try: self.get_session().execute( "CREATE INDEX %s_key on stats (%s);" % (name, name) ) except cassandra.InvalidRequest as e: print " %s" % e.message def destroy_all_the_things(self): # do we REALLY want this method here? or just in the tests? self.get_session().execute("DROP KEYSPACE %s" % self.keyspace()) def destroy_the_tables(self): self.get_session().execute("DROP TABLE stats") def migrate(self): print "initializing cluster %s in %s" % (self.config['NODES'], self.config['KEYSPACE']) self.create_keyspace() self.create_tables() self.create_indicies() print "done." if __name__ == '__main__': app = Flask(__name__) env = Environments(app) env.from_object('whatsup.config') migrator = Migrator(app.config) migrator.migrate()