def create_app():
    app = Flask(__name__)
    app.config.from_object('geomancer.app_config')
    app.session_interface = RedisSessionInterface()
    app.register_blueprint(api)
    app.register_blueprint(views)

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def server_error(e):
        return render_template('error.html'), 500

    @app.errorhandler(413)
    def file_too_large(e):
        return render_template('413.html'), 413
    
    @app.template_filter('string_split')
    def string_split(val, splitter):
        return val.split(splitter)

    if sentry:
        sentry.init_app(app)

    return app
Beispiel #2
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)

    CORS(
        app,
        origins=[
            'http://127.0.0.1:5997',
            'http://127.0.0.1:5998',
            'http://regenerativefood.org',
            'http://www.regenerativefood.org'
        ],
        supports_credentials=True
    )

    from app.lib.database import db
    db.init_app(app)

    from app import views
    views.register(app)

    with app.app_context():
        db.create_all()

    from app.lib.session import SessionInterface
    app.session_interface = SessionInterface()

    return app
Beispiel #3
0
def createApp(name):
    app = Flask(__name__)
    app.config.from_object(config[name])

    lm.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    Markdown(app)
    pagedown.init_app(app)

    from .main import main as mainBluePrint
    app.register_blueprint(mainBluePrint)

    from .auth import auth as authBluePrint
    app.register_blueprint(authBluePrint)

    from .settings import setting as settingBluePrint
    app.register_blueprint(settingBluePrint, url_prefix='/setting')

    from .api_v_1_0 import api as apiBluePrint
    app.register_blueprint(apiBluePrint, url_prefix='/api')

    return app
Beispiel #4
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)
    login_manager.init_app(app)
    pagedown.init_app(app)
    toolbar.init_app(app)

    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')

    @app.route('/secret')
    @login_required
    def secret():
        return 'Only authenticated users are allowed!!!'

    return app
Beispiel #5
0
def create_app(config={}):
    global babel, db, mail, sess
    app = Flask(__name__)
    app.config.from_object('ffdnispdb.default_settings')
    app.config.from_envvar('FFDNISPDB_SETTINGS', True)
    if isinstance(config, dict):
        app.config.update(config)
    else:
        app.config.from_object(config)
    babel.init_app(app)
    babel.localeselector(get_locale)
    db.init_app(app)

    with app.app_context():
        @event.listens_for(db.engine, "connect")
        def connect(sqlite, connection_rec):
            sqlite.enable_load_extension(True)
            sqlite.execute('select load_extension("libspatialite.so")')
            sqlite.enable_load_extension(False)

    app.session_interface = sess
    mail.init_app(app)
    cache.init_app(app)

    from .views import ispdb
    from .views_api import ispdbapi
    app.register_blueprint(ispdb)
    app.register_blueprint(ispdbapi, url_prefix='/api')
    return app
Beispiel #6
0
def create_app(config=None, environment=None):
    app = Flask(__name__)

    # TODO: Get this from a config file
    app.config["MONGODB_SETTINGS"] = {'db': "eatdb"}
    app.config[
        "SECRET_KEY"] = "\x1a\xb1\x9d\x1d\xf2\x01\xa1X\xb8g\xed\x1c\xb3\x0f+s\xbce\xf6\x92\x83'\xf2\xbc\x96\xc6\x18\x03`\xc0\x0c("
    app.config["IV"] = '\xe7\x9d\xc7\xbd\x12l\x88\xc7\xe9D\x93!\xa2B\xed\x91'
    app.config.from_pyfile('settings.cfg', silent=True)
    app.session_interface = MongoSessionInterface(**(app.config["MONGODB_SETTINGS"]))

    with app.app_context():
        from models import db
        db.init_app(app)

        login_manager = LoginManager()

        @login_manager.user_loader
        def load_user(id):
            if id in (None, 'None'):
                return None
            try:
                from models.user import User
                return User.objects(id=id).first()
            except:
                return None

        login_manager.init_app(app)

        from views import register_routes as register_views

        register_views(app)

    return app
Beispiel #7
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)

    CORS(
        app,
        origins=[
            'http://127.0.0.1:5994',
            'http://living-with-django.astex.io'
        ],
        supports_credentials=True
    )

    from blog.lib.database import db
    db.init_app(app)

    from blog import views
    views.register(app)

    with app.app_context():
        db.create_all()

    from blog.lib.session import SessionInterface
    app.session_interface = SessionInterface()

    return app
Beispiel #8
0
def create_app(config_filename='config.default.DevelopmentConfig'):
    app = Flask(__name__)
    app.config.from_object(config_filename)

    app.secret_key = app.config['SECRET_KEY']
    app.permanent_session_lifetime = timedelta(minutes=app.config['SESSION_ALIVE_MINUTES'])
    app.session_interface = ItsdangerousSessionInterface()
    # SOCKET
    # url = '127.0.0.1'
    # client_socket.connect((url, 8000))

    # logging module
    log_filepath = os.path.join(app.config['ROOT_DIR'], 'app_server/log')
    log.init(log_filepath=log_filepath, log_level=app.config['LOG_LEVEL'])
    log.info("CREATE HIMS APP : "+__name__)

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)

    from youngs_server.api.auth_controllers import api_auth
    from youngs_server.api.member_controllers import api_member
    from youngs_server.api.lecture_controllers import api_lecture
    from youngs_server.api.question_controllers import api_question

    app.register_blueprint(api_auth)
    app.register_blueprint(api_member)
    app.register_blueprint(api_lecture)
    app.register_blueprint(api_question)
    return app
def create_app(config_filepath ="resource/config.cfg"):
    app = Flask(__name__)
    #app.config.from_object(__name__)
    #app.config.from_envvar('GRADE_SETTINGS', silent=True)
    
    # 기본 설정은 GradeServer_Config 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 GradeServer_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정 
    from GradeServer.GradeServer_config import GradeServerConfig
    app.config.from_object(GradeServerConfig)
    app.config.from_pyfile(config_filepath, silent=True)
    # Log
    from GradeServer.GradeServer_logger import Log
    Log.init()
    
    # SessionInterface 설정.
    from GradeServer.cache_session import RedisCacheSessionInterface
    app.session_interface = RedisCacheSessionInterface()
    
    # 데이터베이스 처리 
    from GradeServer.database import DBManager
    DBManager.init(app.config['DB_URL'])    
    DBManager.init_db()
    
        # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에 
        # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from GradeServer.controller import *
    from GradeServer.GradeServer_blueprint import GradeServer
    app.register_blueprint(GradeServer)
     
    return app
Beispiel #10
0
def create_app(config_filename='settings.py', config_dict=None):
    """
    Creates a Pjuu WSGI application with the passed in confif_filename.

    config_filename should be one of a Python file as per the default. To
    create one simply copy the settings.py file and change the settings
    to suit yourself

    settings_dict can be used to override any settings inside config_filename.
    This is useful for testing. See run_tests.py for an example
    """
    # Pylint has suggested I dont set config_dict to a empty dict, we now have
    # to check if it is None and then assign an empty dict
    if config_dict is None:  # pragma: no cover
        config_dict = {}

    # Create application
    app = Flask(__name__)

    # Load configuration from the Python file passed as config_filename
    app.config.from_pyfile(config_filename)
    # Override the settings from config_filename, even add new ones :)
    # This is useful for testing, we use it for Travis-CI, see run_tests.py
    app.config.update(config_dict)

    # You can also set an environment variable called PJUU_SETTINGS this will
    # override all other Settings applied to Pjuu so long as you define them
    app.config.from_envvar('PJUU_SETTINGS', silent=True)

    # Sentry logger
    # We now only use Sentry for logging all our in application errors
    # We do not need it if debug is True as we expect there could be errors
    # and we get full visibility.
    if not app.debug:  # pragma: no cover
        sentry.init_app(app)

    # This is the _MAIN_ redis client. ONLY STORE DATA HERE
    redis.init_app(app)

    # Create Flask-Mail
    mail.init_app(app)

    # Create the Redis session interface
    redis_sessions.init_app(app, 'SESSION_REDIS')

    # Set session handler to Redis
    app.session_interface = RedisSessionInterface(redis=redis_sessions)

    with app.app_context():
        # Import all Pjuu stuffs
        # Load Redis LUA scripts, this will also load the scripts into Redis
        import pjuu.lib.lua
        # Endpoints
        import pjuu.pages
        import pjuu.auth.views
        import pjuu.users.views
        import pjuu.posts.views

    # Return a nice shiny new Pjuu WSGI application :)
    return app
Beispiel #11
0
def create_app(package_name, package_path, settings=None):
    app = Flask(package_name,
                instance_relative_config=True,
                template_folder='templates')
    app.config.from_pyfile('conf.py', silent=True)
    app.config.from_object('eGrader.security_config')

    if settings is not None:
        app.config.from_object(settings)

    # init extensions
    db.init_app(app)
    security.init_app(app,
                      SQLAlchemyUserDatastore(db, User, Role),
                      register_blueprint=True,
                      confirm_register_form=ExtendedRegisterForm)
    bootstrap.init_app(app)
    mail.init_app(app)
    webpack.init_app(app)
    socketio.init_app(app)

    # add any jinja2 globals
    app.jinja_env.globals['momentjs'] = MomentJS

    # attach redis sessions
    app.session_interface = RedisSessionInterface()

    # register main blueprints
    app.register_blueprint(dashboard)
    app.register_blueprint(grader)
    app.register_blueprint(api)
    app.register_blueprint(admin)
    app.register_blueprint(viewer)

    return app
Beispiel #12
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)

    CORS(
        app,
        origins=app.config['CORS_ORIGINS'],
        supports_credentials=True
    )

    from app.lib.database import db
    db.init_app(app)

    from app import views
    views.register(app)

    with app.app_context():
        db.create_all()

    from app.lib.session import SessionInterface
    app.session_interface = SessionInterface()

    from app.lib import exceptions
    exceptions.register(app)

    return app
Beispiel #13
0
def create_app(config, is_web=False):
    app = Flask(__name__)
    app.config.from_object(config)
    app.session_interface = RedisSessionInterface()
    register_extensions(app)
    if is_web:
        register_web(app)

    return app
def create_app(db_interface, app_name='testapp', db_name='__test-db__'):
    app = Flask(app_name)
    app.config['SERVER_NAME'] = 'localhost:5000'

    if db_interface == 'pymongo':
        app.config['MONGO_DBNAME'] = db_name
        mongo = PyMongo(app)
        with app.app_context():
            app.session_interface = MongoDBSessionInterface(
                app, mongo.db, 'sessions')
    elif db_interface == 'mongoengine':
        app.config['MONGODB_DB'] = db_name
        mongo = MongoEngine(app)
        app.session_interface = MongoDBSessionInterface(
            app, mongo.connection[app.config['MONGODB_DB']], 'sessions')

    @app.route("/set")
    def set_session():
        session['data'] = request.args['d']
        return 'data'

    @app.route("/setpermanent")
    def set_permanent_session():
        session.permanent = True
        session['data'] = request.args['d']
        return 'data'

    @app.route("/get")
    def get_session():
        return session.get('data', '')

    @app.route("/unicode/set")
    def unicode_set():
        session['foo'] = u'Alpenerstra\xdfe'
        return 'done'

    @app.route("/unicode/get")
    def unicode_get():
        return session['foo']

    return app
 def setUp(self):
     app = Flask(__name__)
     app.session_interface = CheckerSessionInterface()
     app.json_encoder = CustomJSONEncoder
     app.config["SECRET_KEY"] = "test"
     app.add_url_rule("/<step>", view_func=TestWizard.as_view("wizard"))
     app.add_url_rule(
         "/session-expired", endpoint="base.session_expired", view_func=lambda request: "Session expired"
     )
     self.client = app.test_client()
     with self.client.session_transaction() as sess:
         sess.checker["foo"] = "bar"
Beispiel #16
0
 def load_app(self, config):
     """
     Called from the parent class, so we can provide the appropriate flask
     app for this test case.
     """
     app = Flask('test.localhost')
     app.request_class = Request
     app.config.update(config)
     app.register_blueprint(test_views)
     app.central_userdb = UserDB(app.config['MONGO_URI'], 'eduid_am')
     app.session_interface = SessionFactory(app.config)
     return app
Beispiel #17
0
def create_app(config_name="dev"):
    '''
    used to create the admin app instance

    INPUT: none
    OUTPUT: app instance

    '''
    app = Flask(__name__, static_folder='static', template_folder='templates')
    app.config.from_object(config[config_name])
        
    mongo.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    app.session_interface = MongoSessionInterface(db=config[config_name].MONGO_DBNAME)
    
    #ugly temporary hack; server caches classes in app context
    with app.app_context():
        import users.models
        import services.models

    create_admins(app,config[config_name].ADMINS)


    #errorhandlers
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('500.html'), 500

    #general routes
    @app.route('/')
    def homepage():
        return redirect('/home')

    #filters
    def is_hidden_field(field):
        from wtforms import HiddenField
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field

    from .users.views import mod as usersBlueprint
    app.register_blueprint(usersBlueprint,url_prefix='')
    from .services.views import mod as dbstatusBlueprint
    app.register_blueprint(dbstatusBlueprint,url_prefix='/services')
    
    return app
Beispiel #18
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.session_interface = MongoEngineSessionInterface(db)

    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    create_admins(config[config_name].ADMINS)

    #errorhandlers
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('500.html'), 500

    #routes
    @app.route('/login', methods=['GET','POST'])
    def loginpage():
        return redirect(url_for('users.login'))

    @app.route('/')
    @app.route('/home')
    def homepage():
        return redirect(url_for('wall.list'))

    #filters
    @app.template_filter('boolswitch')
    def switchboolean(s):
        var = {True:'DA',False:'NU'}
        return var[s]

    
    from .users.views import mod as users_blueprint
    app.register_blueprint(users_blueprint, url_prefix='/membri')
    from .messages.views import mod as msgs_blueprint
    app.register_blueprint(msgs_blueprint, url_prefix='/mesagerie')
    from .wall.views import mod as wall_blueprint
    app.register_blueprint(wall_blueprint, url_prefix='/home')
    from .projects.views import mod as proj_blueprint
    app.register_blueprint(proj_blueprint, url_prefix='/proiecte')
    from .inventory.views import mod as inv_blueprint
    app.register_blueprint(inv_blueprint, url_prefix='/inventar')
   
    return app
Beispiel #19
0
    def init_app(self, app_name, **kwargs):
        app = Flask(app_name, **kwargs)
        app.config.from_object(self.app_config)
        app.config.from_envvar(self.app_envvar, silent=True)

        self._add_logger(app)
        self._bind_extensions(app)
        self._register_blueprints(app)
        self._register_hooks(app)

        app.session_interface = RedisSessionInterface()
        app.wsgi_app = ProxyFix(app.wsgi_app)
        return app
Beispiel #20
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('api.app_config')
    redis = Redis()
    app.session_interface = RedisSessionInterface(redis=redis)
    if sentry:
        sentry.init_app(app)
    app.register_blueprint(years)
    app.register_blueprint(views)
    app.register_blueprint(segments)
    app.register_blueprint(job_types)
    app.register_blueprint(geo)
    return app
Beispiel #21
0
def create_app(config_filepath='resource/config.cfg'):
    photolog_app = Flask(__name__)

    # 기본 설정은 PhotologConfig 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 PHOTOLOG_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정 
    from photolog.photolog_config import PhotologConfig
    photolog_app.config.from_object(PhotologConfig)
    photolog_app.config.from_pyfile(config_filepath, silent=True)
    print_settings(photolog_app.config.items())
        
    # 로그 초기화
    from photolog.photolog_logger import Log
    log_filepath = os.path.join(photolog_app.root_path, 
                                photolog_app.config['LOG_FILE_PATH'])
    Log.init(log_filepath=log_filepath)
    
    # 데이터베이스 처리 
    from photolog.database import DBManager
    db_filepath = os.path.join(photolog_app.root_path, 
                               photolog_app.config['DB_FILE_PATH'])
    db_url = photolog_app.config['DB_URL'] + db_filepath
    DBManager.init(db_url, eval(photolog_app.config['DB_LOG_FLAG']))    
    DBManager.init_db()
       
    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에 
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from photolog.controller import login
    from photolog.controller import photo_show
    from photolog.controller import photo_upload
    from photolog.controller import register_user
    from photolog.controller import twitter
    
    from photolog.photolog_blueprint import photolog
    photolog_app.register_blueprint(photolog)
    
    # SessionInterface 설정.
    # Redis를 이용한 세션 구현은 cache_session.RedisCacheSessionInterface 임포트하고
    # app.session_interface에 RedisCacheSessionInterface를 할당
    from photolog.cache_session import SimpleCacheSessionInterface
    photolog_app.session_interface = SimpleCacheSessionInterface()
    
    # 공통으로 적용할 HTTP 404과 500 에러 핸들러를 설정
    photolog_app.error_handler_spec[None][404] = not_found
    photolog_app.error_handler_spec[None][500] = server_error
    
    # 페이징 처리를 위한 템플릿 함수
    photolog_app.jinja_env.globals['url_for_other_page'] = \
        url_for_other_page
    
    return photolog_app
Beispiel #22
0
def create_app():
    app = Flask(__name__, template_folder='templates',
                static_folder='static')
    app.config.from_object(config)
    mako.init_app(app)
    db.init_app(app)
    app.session_interface = RedisSessionInterface(cache)
    app.register_blueprint(backend.bp)

    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, OrderedDict((
        ('/j', json_api),
    )))

    return app
Beispiel #23
0
def create_app(config='mongo_mail_web.settings.Prod'):
    """
    TODO: before first request pour redirect vers form domains/mynetwork si aucun
    """
    
    env_config = config_from_env('MMW_SETTINGS', config)
    
    app = Flask(__name__)
    app.config.from_object(env_config)
    
    if PYMONGO2:
        app.config['MONGODB_SETTINGS']['use_greenlets'] = True
        
    app.config['LOGGER_NAME'] = 'mongo_mail_web'
    app._logger = _configure_logging(debug=app.debug, prog_name='mongo_mail_web')    
        
    extensions.db.init_app(app)
    
    _configure_mongolock(app)
    
    extensions.moment.init_app(app)
    _configure_i18n(app)
    
    _configure_security(app)
    admin.init_admin(app, url='/')
    
    _configure_processors(app)
    _configure_themes(app)
    
    geoip_tools.configure_geoip()

    if app.debug:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
    
    _configure_sentry(app)
    
    if app.config.get('SESSION_ENGINE_ENABLE', False):
        from flask_mongoengine import MongoEngineSessionInterface
        app.session_interface = MongoEngineSessionInterface(extensions.db)
        
    error_handlers(app)

    app.wsgi_app = ProxyFix(app.wsgi_app)
    
    tasks.run_all_tasks(completed_pool=app.config.get('TASK_COMPLETED_POOL'),
                        completed_sleep=app.config.get('TASK_COMPLETED_SLEEP'),
                        update_metrics_sleep=app.config.get('TASK_UPDATE_METRICS_SLEEP'))
    
    return app
Beispiel #24
0
def create_app():
	app=Flask(__name__)
	app.config.from_object(config[sysType])
	app.config['DEBUG_TB_PANELS']=['flask_mongoengine.panels.MongoDebugPanel']

	bootstrap.init_app(app)

	mongodb.init_app(app)

	moment.init_app(app)


	toolbar=DebugToolbarExtension(app)

	app.session_interface=MongoEngineSessionInterface(mongodb)

	app.jinja_env.filters['filter_html'] = filter_html

	from .home import home as home_blueprint
	app.register_blueprint(home_blueprint)

	from .meitu import meitu as meitu_blueprint
	app.register_blueprint(meitu_blueprint,url_prefix='/meitu')

	from .life import life as life_blueprint
	app.register_blueprint(life_blueprint,url_prefix='/life')

	from .advert import advert as advert_blueprint
	app.register_blueprint(advert_blueprint,url_prefix='/advert')

	from .think import think as think_blueprint
	app.register_blueprint(think_blueprint,url_prefix='/think')

	from .technology import tech as tech_blueprint
	app.register_blueprint(tech_blueprint,url_prefix='/tech')

	from .book import book as book_blueprint
	app.register_blueprint(book_blueprint,url_prefix='/book')

	from .shop import shop as shop_blueprint
	app.register_blueprint(shop_blueprint,url_prefix='/shop')

	from .collect import collect as collect_blueprint
	app.register_blueprint(collect_blueprint,url_prefix='/collect')

	from .message import message as message_blueprint
	app.register_blueprint(message_blueprint,url_prefix='/message')

	return app
Beispiel #25
0
def create_app(**config_overrides):
    app = Flask(__name__)
    # Load config.
    app.config.from_object('webapp.config')
    # apply overrides
    app.config.update(config_overrides)
    # Setup the database.
    db.init_app(app)
    # Setup security
    app.session_interface = MongoEngineSessionInterface(db)
    user_datastore = MongoEngineUserDatastore(db, User, Role)
    app.security = Security(app, user_datastore)

    register_blueprints(app)
    return app
def create_app(mode = "production"):
	global app
	app = Flask("application")
	app.session_interface = RedisSessionInterface()

	global app_run_args
	app_run_args = {'port': 5000, 'host': '127.0.0.1'}

	if mode == "production":
		app.debug = False
	elif mode == "dev":
		app.debug = True
	else:
		logging.error("Did not recognize mode '%s'" % mode)

	import application.route
Beispiel #27
0
def create_app():
    app = Flask("backercapital")
    app.session_interface = MongoSessionInterface(MONGOHQ_URL)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_ECHO'] = True

    app.config['SECRET_KEY'] = '123456790'

    db = SQLAlchemy(app)
    app.register_blueprint(campaign)
    app.register_blueprint(console)
    app.register_blueprint(www)
    #app.before_request(assign_transaction_id)
    app.teardown_appcontext(shutdown_session)

    return app
Beispiel #28
0
def create_app():
    """Return an instance of the main Flask application."""
    app = Flask(package_name)

    # TODO: do some config
    app.redis = StrictRedis()

    from .error import register_error_handler, html_handler
    register_error_handler(app, html_handler)

    from .session import LazyRedisSessionInterface
    app.session_interface = LazyRedisSessionInterface()

    from .views import views
    app.register_blueprint(views)

    return app
Beispiel #29
0
def create_app(config_filepath='resource/config.cfg'):
    simulation_app = Flask(__name__)

    # 기본 설정은 SimulationConfig 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 Simulation_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정 
    from simulation.simulation_config import SimulationConfig
    simulation_app.config.from_object(SimulationConfig)
    simulation_app.config.from_pyfile(config_filepath, silent=True)

    print_settings(simulation_app.config.iteritems())

	# 로그 초기화
    from simulation.simulation_logger import Log
    log_filepath = os.path.join(simulation_app.root_path, simulation_app.config['LOG_FILE_PATH'])

    Log.init(log_filepath=log_filepath)

    # 데이터베이스 처리 
    from simulation.database import DBManager 
    db_bind = simulation_app.config['DB_BINDS']
    DBManager.init(db_bind, eval(simulation_app.config['DB_LOG_FLAG']))     
    DBManager.init_db() 


    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에 
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from simulation.controller import register_user, login, diary_list, diary_write, file_list

    from simulation.simulation_blueprint import simulationlog
    simulation_app.register_blueprint(simulationlog)
    
    # SessionInterface 설정.
    # Redis를 이용한 세션 구현은 cache_session.RedisCacheSessionInterface 임포트하고
    # app.session_interface에 RedisCacheSessionInterface를 할당
    from simulation.cache_session import SimpleCacheSessionInterface
    simulation_app.session_interface = SimpleCacheSessionInterface()


    # 공통으로 적용할 HTTP 404과 500 에러 핸들러를 설정
    simulation_app.error_handler_spec[None][404] = not_found
    simulation_app.error_handler_spec[None][500] = server_error

    # 페이징 처리를 위한 템플릿 함수
    simulation_app.jinja_env.globals['url_for_other_page'] = url_for_other_page

    return simulation_app
Beispiel #30
0
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN"), logging=True, level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    return app