Esempio n. 1
0
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
Esempio n. 2
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
Esempio n. 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
Esempio n. 4
0
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
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
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
Esempio n. 8
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
Esempio n. 9
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
Esempio n. 10
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
Esempio n. 11
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
Esempio n. 12
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
Esempio n. 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
Esempio n. 15
0
 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"
Esempio n. 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
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 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
Esempio n. 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
Esempio n. 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
Esempio n. 22
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
Esempio n. 23
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
Esempio n. 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
Esempio n. 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
Esempio n. 26
0
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
Esempio n. 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
Esempio n. 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
Esempio n. 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
Esempio n. 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
Esempio n. 31
0
    application_message = get_application_message(message)
#   Display and render application_message
    post_watson_response(application_message['chat'])
    return render_template(CHAT_TEMPLATE, posts=g('POSTS',[]), form=application_message['form'], context=message['context'], stt_token=g('STT_TOKEN', ''), tts_token=g('TTS_TOKEN', ''))

@app.route('/page', methods=['POST'])
def Page_Post():
    global CHAT_TEMPLATE, CURSOR_INPUT, SEARCH_TYPE_INPUT
    form = ''
#   Set vars from hidden form fields
    action = request.form[CURSOR_INPUT]
    search_type = request.form[SEARCH_TYPE_INPUT]
    possible_actions = {'Accept': 0, 'Next': 1, 'Prev': -1, 'Explore': 0}
    shift = possible_actions[action]
    if shift != 0:
        application_response = get_search_response(search_type, shift)
    elif action == 'Accept':
        application_response = 'Thank you for helping to make Watson smarter! What else can I help you with?'
#   Display application_response
    post_watson_response(application_response)
    return render_template(CHAT_TEMPLATE, posts=g('POSTS',[]), form='', stt_token=g('STT_TOKEN', ''), tts_token=g('TTS_TOKEN', ''))

port = os.getenv('PORT', '5000')
if __name__ == "__main__":
    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()
#   app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    app.run(host='0.0.0.0', port=int(port))
    #app.run(host='9.201.15.195', port=int(port))

Esempio n. 32
0
#!/usr/bin/env python3

import datetime
import logging
import os.path
import time
from flask import Flask, session, request, render_template, Response, abort
from server_sessions import ManagedSessionInterface, CachingSessionManager, FileBackedSessionManager

app = Flask(__name__)
app.secret_key = '90m12iu0x7msadkj9bsoads8t53dbcxviorbscjvoiewr'
skip_paths = ()
CACHE_DIR = os.path.expanduser('~/.cache/fsite-server')

app.session_interface = ManagedSessionInterface(
    CachingSessionManager(FileBackedSessionManager(CACHE_DIR, app.secret_key),
                          50), skip_paths, datetime.timedelta(days=1))


@app.route('/', methods=['GET', 'POST'])
def run():
    if request.method == 'POST':
        session['number'] = request.form['number']

    return render_template('index.html', number=session.get('number', ''))


@app.route('/samba', methods=[
    'GET',
])
def dsmb():
Esempio n. 33
0
from flask.ext.mail import Mail
from raven.contrib.flask import Sentry
#from flask.ext.login import LoginManager
from flask import current_app, Blueprint, render_template
from werkzeug.debug import DebuggedApplication
import os.path as op

app = Flask(__name__, static_url_path='/static')
app.config.from_object('config')
app.debug = True
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
Mobility(app)
db = SQLAlchemy(app)
mongo = PyMongo(app)
with app.app_context():
    app.session_interface = MongoDBSessionInterface(app, mongo.db, 'sessions')

admin = Admin(app)
babel = Babel(app)
cache = Cache(app,
              config={
                  'CACHE_TYPE': 'memcached',
                  'CACHE_KEY_PREFIX': 'cache_'
              })
mail = Mail(app)

app.config[
    'SENTRY_DSN'] = 'http://*****:*****@sentry.cubeline.ru/20'
sentry = Sentry(app)

from app import urls, views, models
Esempio n. 34
0
        print(ssd)
        ssstr = cPickle.dumps(ssd)
        self.store.setex(session.sid, self.timeout, ssstr)

        # Refresh the cookie
        response.set_cookie(app.session_cookie_name,
                            session.sid,
                            expires=self.get_expiration_time(app, session),
                            httponly=True,
                            domain=domain)


#########################################################################################
# Create an application
application = Flask(__name__)
application.session_interface = RedisSessionInterface()


#########################################################################################
@application.route("/")
def index():
    session.permanent = False
    if not 'refreshed' in session:
        session['refreshed'] = 0

    text = "You refreshed the page %d times" % (session['refreshed'])
    text += '<br/><a href="/kill">Reset</a>'
    text += '<br/>dbname="%s"' % session.get('dbname', 'NULL')
    session['refreshed'] = session['refreshed'] + 1
    return text
Esempio n. 35
0
            expiration = datetime.utcnow() + timedelta(hours=1)
        self.store.update({'sid': session.sid}, {
            'sid': session.sid,
            'data': session,
            'expiration': expiration
        }, True)

        response.set_cookie(app.session_cookie_name,
                            session.sid,
                            expires=self.get_expiration_time(app, session),
                            httponly=True,
                            domain=domain)


app = Flask(__name__)
app.session_interface = MongoSessionInterface(db='jpub')
app.config.update(SESSION_COOKIE_NAME='jpub_flask_session')


@app.route("/session_in")
def session_signin():
    session['test'] = "abc"

    return "Session Signin"


@app.route("/session_out")
def session_sighout():
    session.clear()
    return "Session Signout"
Esempio n. 36
0
import requests
import os
from sessions import RedisSessionInterface
from datetime import timedelta, datetime, date
from flask import (Flask, render_template, g, redirect, url_for, request,
                   session, abort)

app = Flask(__name__)
app_root = os.path.dirname(os.path.abspath(__file__))
app.session_interface = RedisSessionInterface()
app.secret_key = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)


@app.before_request
def b4req():
    g.user = None
    if ('user' in session):
        g.user = session['user']


@app.route('/')
def index():
    if (not g.user):
        return redirect(url_for('login'))

    return render_template('index.html')


@app.route('/login', methods=['POST', 'GET'])
def login():
def createApp():
    """Set up the application."""
    try:
        # Create application
        app = Flask(__name__, instance_path=CONFIG_PATH)
        local = CONFIG_BROKER['local']
        app.config.from_object(__name__)
        app.config['LOCAL'] = local
        app.config['REST_TRACE'] = CONFIG_SERVICES['rest_trace']
        app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

        # Future: Override config w/ environment variable, if set
        app.config.from_envvar('BROKER_SETTINGS', silent=True)

        # Set parameters
        broker_file_path = CONFIG_BROKER['broker_files']
        AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
        sesEmail.SIGNING_KEY = CONFIG_BROKER['email_token_key']
        sesEmail.isLocal = local
        if sesEmail.isLocal:
            sesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
        # If local, make the email directory if needed
        if local and not os.path.exists(broker_file_path):
            os.makedirs(broker_file_path)

        # When runlocal is true, assume Dynamo is on the same server
        # (should be false for prod)
        JsonResponse.debugMode = app.config['REST_TRACE']

        if CONFIG_SERVICES['cross_origin_url'] == "*":
            cors = CORS(app, supports_credentials=True)
        else:
            cors = CORS(app,
                        supports_credentials=True,
                        origins=CONFIG_SERVICES['cross_origin_url'])
        # Enable AWS Sessions
        app.session_interface = DynamoInterface()
        # Set up bcrypt
        bcrypt = Bcrypt(app)
        # Root will point to index.html
        @app.route("/", methods=["GET"])
        def root():
            return "Broker is running"

        if local:
            localFiles = os.path.join(broker_file_path, "<path:filename>")
            # Only define this route when running locally
            @app.route(localFiles)
            def sendFile(filename):
                if (config["local"]):
                    return send_from_directory(broker_file_path, filename)
        else:
            # For non-local installs, set Dynamo Region
            SessionTable.DYNAMO_REGION = CONFIG_BROKER['aws_region']

        # Add routes for modules here
        add_login_routes(app, bcrypt)

        add_file_routes(app, CONFIG_BROKER['aws_create_temp_credentials'],
                        local, broker_file_path)
        add_user_routes(app, app.config['SYSTEM_EMAIL'], bcrypt)

        SessionTable.LOCAL_PORT = CONFIG_DB['dynamo_port']

        SessionTable.setup(app, local)

        return app

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        trace = traceback.extract_tb(exc_tb, 10)
        CloudLogger.logError('Broker App Level Error: ', e, trace)

        del exc_tb
        raise
Esempio n. 38
0
app_name = 'FlaskApp'

# set redis
my_redis_config = RedisConfig(app_name)
app.config['REDIS_URL'] = my_redis_config.get_redis_url_general()
redis_store = FlaskRedis(app)

# set redis for session management
redis_storage = redis.Redis(
    host=my_redis_config.get_redis_ip_session(),
    port=my_redis_config.get_redis_port_session(),
    db=my_redis_config.get_redis_db_session(),
    charset=my_redis_config.get_redis_charset_session())

app.session_interface = RedisSessionInterface(
    redis=redis_storage,
    key_prefix=my_redis_config.get_key_prefix_session(),
    use_signer=True)

# set db connection with postgres
my_postgres_config = PostgresConfig(app_name)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = my_postgres_config.get_url_general()
db = SQLAlchemy(app)

# set all routes
my_socketio_routes = MySocketIO(app)
my_partials_routes = MyPartials(app)
my_index_routes = MyIndex(app, my_socketio_routes.get_socketio(), db, session,
                          redis_store)

# set celery app
Esempio n. 39
0
def create_app():
    # Factory method to create the app
    prod_app_name = config.get('SERVER_APP')
    my_app = Flask(__name__)
    # set up uploading
    my_app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024  # 1MB
    my_app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
    # Set up sentry logging
    my_app.config['SENTRY_USER_ATTRS'] = ['email']
    try:
        sentry_dsn = config.get('SENTRY_DSN')
        Sentry(my_app, dsn=sentry_dsn)
    except ConfigException as ce:
        logger.warning(ce)
    # set up webpack
    if is_dev_mode():
        manifest_path = '../build/manifest.json'
    else:
        manifest_path = '../server/static/gen/{}/manifest.json'.format(
            prod_app_name)
    webpack_config = {
        'DEBUG': is_dev_mode(),
        'WEBPACK_MANIFEST_PATH': manifest_path
    }
    # caching and CDN config
    my_app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 7 * 24 * 60 * 60
    try:
        cdn_asset_url = config.get('ASSET_URL')
        webpack_config['WEBPACK_ASSETS_URL'] = cdn_asset_url
        logger.info("Asset pipeline: {}".format(cdn_asset_url))
    except ConfigException:
        logger.info("Asset pipeline: no cdn")
    my_app.config.update(webpack_config)
    webpack.init_app(my_app)
    # set up mail sending
    try:
        if config.get('SMTP_ENABLED') == '1':
            mail_config = {     # @see https://pythonhosted.org/Flask-Mail/
                'MAIL_SERVER': config.get('SMTP_SERVER'),
                'MAIL_PORT': int(config.get('SMTP_PORT')),
                'MAIL_USE_SSL': config.get('SMTP_USE_SSL'),
                'MAIL_USERNAME': config.get('SMTP_USER'),
                'MAIL_PASSWORD': config.get('SMTP_PASS'),
            }
            my_app.config.update(mail_config)
            mail.init_app(my_app)
            logger.info('Mailing from {} via {}'.format(
                config.get('SMTP_USER'), config.get('SMTP_SERVER')))
            # need to tell jinja to look in "emails" directory directly for the shared email templates
            # because the `imports` in them don't include relative paths
            my_loader = jinja2.ChoiceLoader([
                my_app.jinja_loader,
                jinja2.FileSystemLoader([
                    os.path.join(base_dir, 'server', 'templates'),
                    os.path.join(base_dir, 'server', 'templates', 'emails')
                ])
            ])
            my_app.jinja_loader = my_loader
        else:
            logger.warning("Mail configured, but not enabled")
    except ConfigException as ce:
        logger.exception(ce)
        logger.warning("No mail configured")
    # set up thread pooling
    my_app.config['EXECUTOR_PROPAGATE_EXCEPTIONS'] = True
    my_app.config['EXECUTOR_MAX_WORKERS'] = 20
    # app.config['EXECUTOR_TYPE'] = 'thread' # valid options - 'thread' (default) or 'process'
    # set up user login
    cookie_domain = config.get('COOKIE_DOMAIN')
    my_app.config['SESSION_COOKIE_NAME'] = "mc_session"
    my_app.config['REMEMBER_COOKIE_NAME'] = "mc_remember_token"
    if cookie_domain != 'localhost':  # can't set cookie domain on localhost
        my_app.config['SESSION_COOKIE_DOMAIN'] = cookie_domain
        my_app.config['REMEMBER_COOKIE_DOMAIN'] = cookie_domain
    # connect to the shared session storage
    my_app.session_interface = RedisSessionInterface(
        redis.StrictRedis.from_url(config.get('SESSION_REDIS_URL')))

    my_app.cli.add_command(sync_frontend_db)

    return my_app
Esempio n. 40
0
def create_app(config='config.ProductionDevelopmentConfig', apptype='profi'):
    app = Flask(__name__, static_folder='./static')

    app.config.from_object(config)
    # babel = Babel(app)

    app.teardown_request(close_database)
    app.config['DEBUG'] = True

    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)

    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():
            # class RelEnvironment(jinja2.Environment):
            #     """Override join_path() to enable relative template paths."""
            #     def join_path(self, template, parent):
            #         return os.path.join(os.path.dirname(parent), template)

            from profapp.models.portal import Portal
            portal = g.db.query(Portal).filter_by(host=request.host).one()
            g.portal = portal
            g.portal_id = portal.id
            g.portal_layout_path = portal.layout.path
            g.lang = g.portal.lang if g.portal else g.user_dict['lang']

        app.before_request(load_portal)
        from profapp.controllers.blueprints_register import register_front as register_blueprints_front
        register_blueprints_front(app)

    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)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'basic'

    @login_manager.user_loader
    def load_user_manager(user_id):
        return g.db.query(User).get(user_id)

    csrf.init_app(app)

    # read this: http://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
    # app.jinja_env.globals.update(flask_endpoint_to_angular=flask_endpoint_to_angular)

    app.jinja_env.globals.update(raw_url_for=raw_url_for)
    app.jinja_env.globals.update(pre=pre)
    app.jinja_env.globals.update(translates=translates)
    app.jinja_env.globals.update(fileUrl=fileUrl)
    app.jinja_env.globals.update(prImage=prImage)
    app.jinja_env.globals.update(url_page=url_page)
    app.jinja_env.globals.update(config_variables=config_variables)
    app.jinja_env.globals.update(_=translate_phrase)
    app.jinja_env.globals.update(__=translate_html)
    app.jinja_env.globals.update(
        tinymce_format_groups=HtmlHelper.tinymce_format_groups)
    app.jinja_env.globals.update(pr_help_tooltip=pr_help_tooltip)

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

    # see: http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
    # Flask will automatically remove database sessions at the end of the
    # request or when the application shuts down:
    # from db_init import db_session

    # @app.teardown_appcontext
    # def shutdown_session(exception=None):
    #     try:
    #         db_session.commit()
    #     except Exception:
    #         session.rollback()
    #         raise
    #     finally:
    #         session.close()  # optional, depends on use case
    #     # db_session.remove()

    session_opts = {
        'session.type': 'ext:memcached',
        'session.url': 'memcached.profi:11211'
    }

    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            _session = request.environ['beaker.session']
            return _session

        def save_session(self, app, session, response):
            session.save()

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    return app
Esempio n. 41
0
    _app_ctx_stack,
    Response,
    after_this_request,
)

import memcache
from flask_memcache_session import Session
from werkzeug.contrib.fixers import ProxyFix

import json, os, hashlib, tempfile, subprocess

config = {}

app = Flask(__name__, static_url_path='')
app.cache = memcache.Client(['localhost:11211'], debug=0)
app.session_interface = Session()
app.session_cookie_name = "isucon_session"
app.wsgi_app = ProxyFix(app.wsgi_app)


def load_config():
    global config
    print("Loading configuration")
    env = os.environ.get('ISUCON_ENV') or 'local'
    with open('../config/' + env + '.json') as fp:
        config = json.load(fp)


def connect_db():
    global config
    host = config['database']['host']
from cassandra.cluster import Cluster
from flask import Flask, session

from cassandra_flask_sessions import CassandraSessionInterface, AbstractConnectionProvider


class ConnectionProvider(AbstractConnectionProvider):

    _connection = Cluster(['127.0.0.1']).connect('tests')

    def get_connection(self):
        return self._connection


_app = Flask(__name__)
_app.session_interface = CassandraSessionInterface(ConnectionProvider())


@_app.route('/set/<name>')
def set_session(name):
    session['name'] = name
    return 'ok'


@_app.route('/get')
def get_session():
    return json.dumps(dict(session))


@_app.route('/delete')
def delete_session():
Esempio n. 43
0
register_models(admin_init)
admin_init.init_app(app)

# Flask SocketIO
monkey.patch_all()
socketio = SocketIO(app)

# Flask Images
images = Images(app)

# Debug Toolbar
toolbar = DebugToolbarExtension(app)

# Redis
r = redis.StrictRedis(*config.REDIS_CONFIG)
app.session_interface = RedisSessionInterface(r, 'session:')

from Dater.application.toRedis import *

next_sid()
sids_and_logins()
timezones()
# all_to_redis()  # import default data to Redis

# Add views blueprints

from Dater.admin import mod as admin_mod
from Dater.view import mod as views_mod

app.register_blueprint(admin_mod)
app.register_blueprint(views_mod)
Esempio n. 44
0
File: app.py Progetto: bodik/sner4
def create_app(config_file=None, config_env='SNER_CONFIG'):
    """flask application factory"""

    app = Flask('sner.server')
    app.config.update(DEFAULT_CONFIG)  # default config
    app.config.update(config_from_yaml(config_file or '/etc/sner.yaml'))  # service configuration
    app.config.update(config_from_yaml(os.environ.get(config_env)))  # wsgi/container config

    app.session_interface = FilesystemSessionInterface(os.path.join(app.config['SNER_VAR'], 'sessions'), app.config['SNER_SESSION_IDLETIME'])

    db.init_app(app)
    jsglue.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login_route'
    login_manager.login_message = 'Not logged in'
    login_manager.login_message_category = 'warning'
    webauthn.init_app(app)

    # load sner.plugin components
    load_agent_plugins()
    load_parser_plugins()

    app.register_blueprint(api_blueprint, url_prefix='/api')
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(scheduler_blueprint, url_prefix='/scheduler')
    app.register_blueprint(storage_blueprint, url_prefix='/storage')
    app.register_blueprint(visuals_blueprint, url_prefix='/visuals')

    app.cli.add_command(auth_command)
    app.cli.add_command(db_command)
    app.cli.add_command(planner_command)
    app.cli.add_command(psql_command)
    app.cli.add_command(scheduler_command)
    app.cli.add_command(storage_command)

    @app.template_filter('datetime')
    def format_datetime(value, fmt='%Y-%m-%dT%H:%M:%S'):  # pylint: disable=unused-variable
        """Format a datetime"""
        if value is None:
            return ''
        return value.strftime(fmt)

    @app.template_filter('json_indent')
    def json_indent(data):  # pylint: disable=unused-variable
        """parse and format json"""
        try:
            return json.dumps(json.loads(data), sort_keys=True, indent=4)
        except ValueError:
            return data

    # globaly enable flask_wtf csrf token helper
    # least intrusive way to pass token into every view without enforcing csrf on all routes
    app.add_template_global(name='csrf_token', f=generate_csrf)

    @app.shell_context_processor
    def make_shell_context():  # pylint: disable=unused-variable
        return {
            'app': app, 'db': db, 'func': func,
            'Excl': Excl, 'ExclFamily': ExclFamily, 'Job': Job, 'Queue': Queue, 'Target': Target,
            'Host': Host, 'Note': Note, 'Service': Service, 'Vuln': Vuln,
            'User': User, 'WebauthnCredential': WebauthnCredential}

    @app.route('/')
    def index_route():  # pylint: disable=unused-variable
        return render_template('index.html')

    return app
Esempio n. 45
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: "liuyouyuan"
# Date: 2018/5/31

from flask import Flask
from flask import session
from session import MySessionInterface

app = Flask(__name__)

app.secret_key = 'asdWhuDW!@##%bxwy'
app.session_interface = MySessionInterface()


@app.route('/login', methods=['GET', "POST"])
def login():
    print(session)
    session['user1'] = 'lyy'
    session['user2'] = 'yy'
    del session['user2']
    print(session)
    return "test mysession"


if __name__ == '__main__':
    app.run()
Esempio n. 46
0
                       'CACHE_KEY_PREFIX':
                       cache_prefix,
                       'CACHE_DEFAULT_TIMEOUT':
                       cache_timeout,
                       'CACHE_REDIS_HOST':
                       get_env_variable("DATAVIVA_REDIS_HOST", "localhost"),
                       'CACHE_REDIS_PORT':
                       get_env_variable("DATAVIVA_REDIS_PORT", 6379),
                       'CACHE_REDIS_PASSWORD':
                       get_env_variable("DATAVIVA_REDIS_PW", None)
                   })

# Set session store as server side (Redis)
redis_sesh = RedisSessionInterface(view_cache, "session:")
if redis_sesh.redis:
    app.session_interface = redis_sesh

# Global Latest Year Variables
from dataviva.stats.util import get_or_set_years

__year_range__ = get_or_set_years(view_cache, "general:data_years")

# login manager for user management
lm = LoginManager()
lm.setup_app(app)

# babel configuration for lang support
babel = Babel(app)

# add a few extra template filters to jinja
app.jinja_env.globals['moment_js'] = jinja_momentjs
Esempio n. 47
0
from flask import Flask, session
from flask_mongoengine import MongoEngine, MongoEngineSessionInterface
from flask_debugtoolbar import DebugToolbarExtension
from datetime import timedelta
from keras.models import load_model
import tensorflow as tf

# Flask init
app = Flask(__name__)
app.config.from_pyfile('./config.py')

# Connection to database init
database = MongoEngine(app)
toolbar = DebugToolbarExtension(app)
app.session_interface = MongoEngineSessionInterface(database)
app.permanent_session_lifetime = timedelta(**app.config['SESSION_LIFETIME'])

model = load_model('network')
graph = tf.get_default_graph()

# Start server
from route import *
if __name__ == '__main__':
    app.run(host=app.config['HOST'], port=app.config['PORT'])
Esempio n. 48
0
from flask.globals import request
from flask.helpers import flash
from flask.templating import render_template
from functools import wraps
from MySessionInterface import MySimpleCacheSessionInterface
# from cache_session import SimpleCacheSessionInterface
from MySessionInterface2 import SimpleCacheSessioninterface

reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
app.config['SESSION_COOKIE_NAME'] = 'my_session'
app.config['PERMANENT_SESSION_LIFETIME'] = 1 * 60
# app.session_interface = MySessionInterface()
app.session_interface = MySimpleCacheSessionInterface()
# app.secret_key = 'asaaaaadf'

def login_required(f):
    '''
        로그인 상태 체크 데코레이터
    :param f:
    :return:
    '''

    @wraps(f)
    def deco_func(*args, **kwargs):
        try:
            session_key = request.cookies.get(app.config['SESSION_COOKIE_NAME'])

            is_login = False
Esempio n. 49
0
    to_snake_case,
    title_dict,
    insert_or_not,
    JSONEncoder,
    get_by_imdb_id,
    insert_or_update_movie_user,
)

app = Flask(__name__)

# Use flask_pymongo to set up mongo connection
# app.config['MONGODB_NAME'] = bingeworthy_db
app.config["MONGO_URI"] = MONGO_URI
mongo = PyMongo(app)

app.session_interface = ItsDangerousSessionInterface()
app.secret_key = SECRET_KEY


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/login", methods=[
    'POST',
])
def send():
    if request.method == 'POST':
        users = mongo.db.users
Esempio n. 50
0
from redisession import RedisSessionInterface

sys.path.append(
    os.path.dirname(os.path.realpath(__file__)) + "/../../../backend/")

import worker  # NOQA

consumer_token = ConsumerToken(consumer_key, consumer_secret)
handshaker = Handshaker(api_url, consumer_token)

redisconnection = Redis(host=redis_host, db=3, password=redis_pw)

app = Flask(__name__)

app.session_interface = RedisSessionInterface(redisconnection)


@app.errorhandler(Exception)
def all_exception_handler(error):
    """Handle an exception and show the traceback to error page."""
    return 'Please notify [[commons:User:Zhuyifei1999]]: ' + \
        traceback.format_exc(), 500


def check_banned():
    """Check for banned cases."""
    # Check for WP0 traffic
    if request.headers.get('X-Carrier'):
        return 'Wikipedia zero case, Phabricator:T129845'
Esempio n. 51
0
app.config['LDAP_GET_GROUP_ATTRIBUTES'] = os.environ.get(
    'LDAP_GET_GROUP_ATTRIBUTES', '*')  # LDAP_GROUP_NAME_ATTRIBUTE

app.config['DEBUG'] = os.environ.get('FLASK_ENV', '') == 'development'
if app.config['DEBUG']:
    logging.getLogger('flask_ldap3_login').setLevel(logging.DEBUG)

login_manager = LoginManager(app)  # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)  # Setup a LDAP3 Login Manager.

if os.environ.get('TENANT_HEADER'):
    app.wsgi_app = TenantPrefixMiddleware(app.wsgi_app,
                                          os.environ.get('TENANT_HEADER'))

if os.environ.get('TENANT_HEADER') or os.environ.get('TENANT_URL_RE'):
    app.session_interface = TenantSessionInterface(os.environ)

# Create a dictionary to store the users in when they authenticate.
users = {}


# Declare an Object Model for the user, and make it comply with the
# flask-login UserMixin mixin.
class User(UserMixin):
    def __init__(self, dn, username, info, groups):
        self.dn = dn

        # NOTE: get original LDAP username,
        #       as login username may be case insensitive
        ldap_username = info.get(LDAP_USER_LOGIN_ATTR)
        if ldap_username and isinstance(ldap_username, list):
Esempio n. 52
0
import flask_login
from flask import Flask
from flask_babel import Babel
from flask_sqlalchemy import SQLAlchemy
from werkzeug.contrib.cache import MemcachedCache

from .session import CacheSessionInterface

# 应用
app = Flask(__name__)
app.config.from_object('config')

# 缓存
cache = MemcachedCache(app.config['MEMCACHE_SERVERS'])
app.session_interface = CacheSessionInterface(cache)

# 国际化和本地化
babel = Babel(app)

# 数据库
db = SQLAlchemy(app)

# 日志
# logging.basicConfig(level=logging.DEBUG)
handler = RotatingFileHandler('app.log',
                              maxBytes=20 * 1024 * 1024,
                              encoding='utf-8')
handler.setLevel(logging.DEBUG)
handler.setFormatter(
    logging.Formatter(
Esempio n. 53
0
				#		SecureCookieSessionInterface().save_session(self, app, session, response)
				# 	由于默认app中的session_interface=MySessionInterFace()
				#		MySessionInterFace().save_session(self, app, session, response)
			
		- flask-session组件 
			- 使用:
				from flask import Flask,session
				from flask_session import RedisSessionInterface

				app = Flask(__name__)
				app.secret_key = 'suijksdfsd'
				
				# 方式一
				from redis import Redis
				conn = Redis()
				app.session_interface = RedisSessionInterface(conn,key_prefix='__',use_signer=False)
				
				# 方式二
				from redis import Redis
				from flask.ext.session import Session
				app.config['SESSION_TYPE'] = 'redis'
				app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379')
				Session(app)


				@app.route('/')
				def index():
					session['xxx'] = 123
					return 'Index'

Esempio n. 54
0
from flask.ext.mail import Mail

# Create and name Flask app
app = Flask("ResumeMeApp")

# database connection
app.config['MONGODB_SETTINGS'] = {
    'HOST': os.environ.get('MONGOLAB_URI'),
    'DB': 'test'
}
app.config['SECRET_KEY'] = 'This string will be replaced'

app.debug = os.environ.get('DEBUG', True)

db = MongoEngine(app)  # connect MongoEngine with Flask App
app.session_interface = MongoEngineSessionInterface(
    db)  # sessions w/ mongoengine

# Flask BCrypt will be used to salt the user password
flask_bcrypt = Bcrypt(app)

# Adding Bootstrap Support
bootstrap = Bootstrap(app)

# Adding momentjs support
moment = Moment(app)

# Associate Flask-Login manager with current app
login_manager = LoginManager()
login_manager.init_app(app)

# Adding Mail Support
Esempio n. 55
0
#-*- coding utf-8 -*-
from flask import Flask, session
from flask import render_template
from flask import request
from lib.redis_session import *
import pymysql
from flask_s3 import FlaskS3
import boto
from boto.s3.key import Key
from flask import jsonify
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
app.session_interface = RedisSessionInterface(host="<REDISS_ENDPOINT>")

AWS_ACCESS_KEY_ID = '<AWS_ACCESS_KEY_ID>'
AWS_SECRET_ACCESS_KEY = '<AWS_SECRET_ACCESS_KEY>'
app.config['FLASKS3_BUCKET_NAME'] = '<FLASKS3_BUCKET_NAME>'
app.config['AWS_ACCESS_KEY_ID'] = AWS_ACCESS_KEY_ID
app.config['AWS_SECRET_ACCESS_KEY'] = AWS_SECRET_ACCESS_KEY
app.config['FLASKS3_REGION'] = '<FLASKS3_REGION>'
app.config['FLASKS3_CDN_DOMAIN'] = 'https://s3.'+app.config['FLASKS3_REGION']+'.amazonaws.com'
app.config['FLASKS3_BUCKET_DOMAIN'] = app.config['FLASKS3_CDN_DOMAIN']+'/'+app.config['FLASKS3_BUCKET_NAME']

app.config['FLASKS3_FORCE_MIMETYPE'] = True

s3 = FlaskS3(app)

Esempio n. 56
0
def create_app():
    """Set up the application."""
    flask_app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    flask_app.config.from_object(__name__)
    flask_app.config['LOCAL'] = local
    flask_app.debug = CONFIG_SERVICES['debug']
    flask_app.env = 'development' if CONFIG_SERVICES['debug'] else 'production'
    flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    flask_app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    SesEmail.is_local = local
    if SesEmail.is_local:
        SesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = flask_app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id")
    else:
        CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
             allow_headers="*", expose_headers="X-Session-Id")
    # Enable DB session table handling
    flask_app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(flask_app)

    @flask_app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @flask_app.before_request
    def before_request():
        # Set global value for local
        g.is_local = local
        sess = GlobalDB.db().session
        # setup user
        g.user = None
        if session.get('name') is not None:
            g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none()

    # Root will point to index.html
    @flask_app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @flask_app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @flask_app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(flask_app, bcrypt)

    add_file_routes(flask_app, local, broker_file_path)
    add_generation_routes(flask_app, local, broker_file_path)
    add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(flask_app)
    add_exception_handlers(flask_app)
    return flask_app
Esempio n. 57
0
from flask import Flask, jsonify, request, render_template, redirect
from flask_jwt_extended import JWTManager
from flask_mail import Mail
from flask_mongoengine import MongoEngine, MongoEngineSessionInterface
from flask_debugtoolbar import DebugToolbarExtension

from weather_api import get_local_time, query_api, query_advanced_api
from views.token import token
from views.api import api
from views.index import index

app = Flask(__name__)
app.config.from_object("config.ProductionConfig")

app.register_blueprint(index)
app.register_blueprint(api)
app.register_blueprint(token)

jwt = JWTManager(app)

db = MongoEngine()
db.init_app(app)

app.session_interface = MongoEngineSessionInterface(db)
toolbar = DebugToolbarExtension(app)
toolbar.init_app(app)

if __name__ == "__main__":
    app.run(host='0.0.0.0')
Esempio n. 58
0
            return
        val = self.serializer.dumps(dict(session))
        session_db = FlaskSession.change(session.sid, val)
        db_session.add(session_db)
        db_session.commit()        
        
        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)

        response.set_cookie(app.session_cookie_name, session.sid,
                            expires=expires, httponly=httponly,
                            domain=domain, secure=secure)

app = Flask(__name__)
app.session_interface = SQLAlchemySessionInterface()
app.config.update(
    SECRET_KEY='F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT',
    SESSION_COOKIE_NAME='jpub_flask_session'
)

@app.route("/session_in")
def session_signin():
    session['test'] = "abc"
    
    return "Session Signin"

@app.route("/session_out")
def session_sighout():
    session.clear()
    return "Session Signout"
Esempio n. 59
0
import os
import psycopg2
from flask_github import GitHub
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

from derp.picklesession import PickleSessionInterface

# globals
app = Flask(__name__)  # instantiate the app here so it can be run as a module

app.config.from_pyfile('CONFIG.py')

db = SQLAlchemy(app)

path = '/dev/shm/derp_sessions'
if not os.path.exists(path):
    os.mkdir(path)
    os.chmod(path, int('700', 8))

app.session_interface = PickleSessionInterface(path)

github = GitHub(app)
import derp.util

app.jinja_env.globals['breadcrumb'] = derp.util.breadcrumb

import derp.models
import derp.views
Esempio n. 60
0
def create_app():
    from flask import Flask
    from config import SECRET_KEY, DB_URI, RABBIT_URL, UPLOAD_DIR
    log("app.py:CreateApp", "Started..")
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['USE_RELOADER'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = SECRET_KEY

    # Even though we don't set a remember_me cookie, if anyone figured out how to create one it'd be bad news. We need
    # to make sure we won't accept a remember me cookie, so we set the name of the cookie we're looking for to
    # something random at startup. Probably a better way to do this, but this works for now.
    app.config['REMEMBER_COOKIE_NAME'] = secrets.token_urlsafe(64)

    log("app.py:CreateApp", "Initializing DB..")
    from backend.database import db
    db.init_app(app)

    log("app.py:CreateApp", "Creating API..")
    from flask_restful import Api
    api = Api(prefix='/api/v1')

    # REST imports
    from apis.rest.agent import AgentEndpoint
    from apis.rest.agent_commands import AgentCommandEndpoint
    from apis.rest.agent_checkin import AgentCheckinEndpoint
    from apis.rest.agent_task import AgentTaskEndpoint
    from apis.rest.agent_type import AgentTypeEndpoint
    from apis.rest.console import ConsoleAgentEndpoint, ConsoleTaskEndpoint
    from apis.rest.error_message import ErrorMessageEndpoint
    from apis.rest.faction_file import FactionFileEndpoint, FactionFileDownloadEndpoint, FactionFileBytesEndpoint
    from apis.rest.ioc import IOCEndpoint
    from apis.rest.payload import PayloadEndpoint, PayloadFileEndpoint
    from apis.rest.staging import StagingEndpoint
    from apis.rest.transport import TransportEndpoint
    from apis.rest.user import LoginEndpoint, ChangePasswordEndpoint, ApiKeyEndpoint, UserEndpoint, \
        UserRoleEndpoint

    # Agent REST endpoints
    log("app.py:CreateApp", "Registering Endpoints..")
    api.add_resource(AgentEndpoint, '/agent/', '/agent/<int:agent_id>/')
    api.add_resource(AgentCheckinEndpoint,
                     '/agent/<string:agent_name>/checkin/')
    api.add_resource(AgentTypeEndpoint, '/agent/type/',
                     '/agent/type/<int:agent_type_id>/')
    api.add_resource(ConsoleAgentEndpoint, '/agent/<int:agent_id>/console/')
    api.add_resource(AgentCommandEndpoint, '/agent/<int:agent_id>/commands/')

    # User REST endpoints
    api.add_resource(LoginEndpoint, '/login/')
    api.add_resource(UserEndpoint, '/user/', '/user/<int:user_id>/')
    api.add_resource(ChangePasswordEndpoint, '/user/<int:user_id>/password/')
    api.add_resource(ApiKeyEndpoint, '/user/<int:user_id>/apikey/',
                     '/user/<int:user_id>/apikey/<int:api_key_id>/')
    api.add_resource(UserRoleEndpoint, '/user/role/',
                     '/user/role/<int:user_role_id>/')

    # Task REST endpoints
    api.add_resource(AgentTaskEndpoint, '/task/', '/task/<int:agent_task_id>/')
    api.add_resource(ConsoleTaskEndpoint, '/task/<int:agent_task_id>/console/')

    # Faction FIle Endpoint
    api.add_resource(FactionFileEndpoint, '/file/',
                     '/file/<string:faction_file_name>')
    api.add_resource(FactionFileDownloadEndpoint,
                     '/file/<string:faction_file_name>/download/')
    api.add_resource(FactionFileBytesEndpoint,
                     '/file/<string:faction_file_name>/bytes/')

    # Misc REST endpoints
    api.add_resource(ErrorMessageEndpoint, '/errors/',
                     '/errors/<int:error_message_id>')
    api.add_resource(IOCEndpoint, '/ioc/', '/ioc/<int:ioc_id>/')
    api.add_resource(PayloadEndpoint, '/payload/',
                     '/payload/<int:staging_config_id>/')
    api.add_resource(PayloadFileEndpoint, '/payload/<int:payload_id>/file/')
    api.add_resource(StagingEndpoint, '/staging/',
                     '/staging/<string:payload_name>/<string:staging_id>/')
    api.add_resource(TransportEndpoint, '/transport/',
                     '/transport/<int:transport_id>/')

    api.init_app(app)

    log("app.py:CreateApp", "Setting up CORS..")
    from flask_cors import CORS
    CORS(app, supports_credentials=dev)

    log("app.py:CreateApp", "Setting up Cache..")
    from backend.cache import cache
    cache.init_app(app)

    log("app.py:CreateApp", "Setting up Login Manager..")
    from models.user import login_manager, ApiSessionInterface
    login_manager.init_app(app)

    # Disable Session Cookies
    log("app.py:CreateApp", "Updating Session Interface..")
    app.session_interface = ApiSessionInterface()

    log("app.py:CreateApp", "Setting up socketio..")
    # You can add extra logging around socketio by setting the following options here: logger=True, engineio_logger=True
    socketio.init_app(app,
                      host='0.0.0.0',
                      manage_session=False,
                      message_queue=RABBIT_URL,
                      channel="ConsoleMessages",
                      cors_allowed_origins="*")

    from backend.rabbitmq import rabbit_consumer
    rabbit_consumer.socketio = socketio
    socketio.start_background_task(target=rabbit_consumer.process_data_events)

    # Check Upload Dir
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)
    log("app.py:CreateApp", "Finished.")
    return app