Example #1
0
def create_app(name=__name__, config={},
               static_folder='transporter/static',
               template_folder=template_dir):
    """NOTE: `db_uri` is only a temporary solution. It shall be replaced by
    something more robust."""
    app = Flask(name, static_folder=static_folder,
                template_folder=template_folder)
    app.secret_key = 'secret'
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URI')
    app.config['REDIS_URL'] = os.environ.get('REDIS_URL')
    app.config['DEBUG'] = True

    app.config.update(config)

    redis_store.init_app(app)

    from transporter.models import db
    db.init_app(app)

    from transporter.main import main_module
    from transporter.api import api_module
    app.register_blueprint(main_module, url_prefix='/')
    app.register_blueprint(api_module, url_prefix='/api')

    return app
Example #2
0
    def setUp(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['DEBUG'] = True
        app.config['TRAP_HTTP_EXCEPTIONS'] = True

        secret_key = u'really big secret'
        token_manager = TokenManager(secret_key)

        token_auth = TokenAuth(secret_key)

        @app.route('/token')
        def get_token():
            user = 'test_user'
            token = token_manager.generate(user).decode('utf-8')
            doc = {'token': token}
            return jsonify(doc)

        @app.route('/')
        def root():
            return jsonify({'message': 'OK'})

        @app.route('/token_required')
        @token_auth.token_required
        def token_required():
            response = jsonify({'message': 'OK'})
            response.status_code = 200
            return response

        self.app = app
        self.client = app.test_client()
        self.secret_key = secret_key
        self.token_manager = token_manager

        return self.app
Example #3
0
    def test_will_prettyprint_json_in_debug_mode(self):
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return {'foo': 'bar', 'baz': 'asdf'}

        api.add_resource(Foo1, '/foo', endpoint='bar')

        with app.test_client() as client:
            foo = client.get('/foo')

            # Python's dictionaries have random order (as of "new" Pythons,
            # anyway), so we can't verify the actual output here.  We just
            # assert that they're properly prettyprinted.
            lines = foo.data.splitlines()
            lines = [line.decode() for line in lines]
            self.assertEquals("{", lines[0])
            self.assertTrue(lines[1].startswith('    '))
            self.assertTrue(lines[2].startswith('    '))
            self.assertEquals("}", lines[3])

            # Assert our trailing newline.
            self.assertTrue(foo.data.endswith(b'\n'))
Example #4
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = "testing..."
        del app.logger.handlers[0]
        # sqlalchemy flask
        self.base = declarative_base()
        self.engine = create_engine('sqlite://')
        self.session = scoped_session(sessionmaker(autocommit=False,
                                                   autoflush=False,
                                                   bind=self.engine))
        self.app = app
        self._ctx = self.app.test_request_context()
        self._ctx.push()
        self.client = self.app.test_client()

        # Add an error handler that returns straight LeverException
        # recommendations
        @self.app.errorhandler(LeverException)
        def handler(exc):
            tb = exc.extra.pop('tb', None)
            self.app.logger.debug("Lever Exception Thrown!\n"
                                  "Extra: {0}\nEnd User: {1}"
                                  .format(exc.extra, exc.end_user),
                                    exc_info=True)
            if tb:
                self.app.logger.debug("Traceback from lever exception:"
                                      "\n{0}".format(tb.replace('\\n', '\n')))
            return jsonify(**exc.end_user), exc.code

        return app
Example #5
0
def create_barebones_app(object_name, env):
    app = Flask(__name__)

    # set config
    app.config.from_object(object_name)
    app.config['ENV'] = env
    app.config['DEBUG'] = False if env=="prod" else True

    # register all custom jinja filters
    for f in jinja_filters:
        app.jinja_env.filters[f[0]] = f[1]

    #init the cache
    cache.init_app(app)

    #init SQLAlchemy
    db.init_app(app)

    #init celery 
    celery.config_from_object(app.config)

    #init Orthanc
    orthanc.init_app(app)

    #init logins
    lm.init_app(app)

    return app
Example #6
0
def create_app():
    global app
    global db
    global login_manager

    # Flask
    app = Flask(__name__,
                static_folder='static/dist/',
                static_url_path='/static')
    app.config.from_object('config.flask_config')

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Login
    login_manager = LoginManager(app)
    login_manager.login_view = 'users.login'

    # Debug
    app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug')

    @login_manager.user_loader
    def load_user(userid):
        from models import User
        return User.query.get(userid)

    from app.models import AnonymousUser
    login_manager.anonymous_user = AnonymousUser

    register_blueprints(app)
    return app, db
Example #7
0
 def create_app(self):
     app = Flask('test')
     app.register_blueprint(blueprint, url_prefix='/bbg')
     app.config['DEBUG'] = True
     app.config['TESTING'] = True
     app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = True
     return app
Example #8
0
def create_app(config=None):
    app = Flask(__name__)

    app.config['SECRET_KEY'] = '129iv3n91283nv9812n3v89q2nnv9iaszv978n98qwe7z897d'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres@localhost/mooddiaryDb'
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/mooddiary.db'

    app.config['DEBUG'] = True
    app.config['ASSETS_DEBUG'] = True
    app.config['LESS_BIN'] = os.path.realpath(os.path.join(os.path.dirname(__file__), '../node_modules/less/bin/lessc'))

    app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=28)
    app.config['JWT_ALGORITHM'] = 'HS512'

    app.config['RECAPTCHA_SECRET_KEY'] = '6LdSswwTAAAAADs20eK6NqYaeppxIWm-gJrpto0l'
    app.config['RECAPTCHA_PUBLIC_KEY'] = '6LdSswwTAAAAABTZq5Za_0blmaSpcg-dFcqaGda9'

    if config:
        app.config.from_object(config)

    db.init_app(app)
    migrate.init_app(app, db)
    assets.init_app(app)
    jwt.init_app(app)

    assets.register('js', js)
    assets.register('css', css)

    app.register_blueprint(main)
    app.register_blueprint(api, url_prefix='/api')
    app.register_blueprint(auth, url_prefix='/auth')

    return app
Example #9
0
def create_app():
    app = Flask(__name__)

    register_blueprints(app)
    register_extensions(app)
    register_jinja_funcs(app)

    # Create modules
    # the debug toolbar is only enabled in debug mode
    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['youremail@yourdomain.com'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'
    
    app.config['DATABASE_CONNECT_OPTIONS'] = {}

    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)
    
    return app
Example #10
0
 def setUp(self):
     """Setup up."""
     app = Flask(__name__)
     app.config['DEBUG'] = True
     app.config['TESTING'] = True
     app.logger.disabled = True
     self.app = app
Example #11
0
def create_app(test_mode=False):
    app = Flask(
        __name__,
        static_url_path='/static',
        static_folder='static',
        instance_relative_config=False)

    app.config.from_object(rq_dashboard.default_settings)
    app.config.from_object(rq_scheduler_dashboard.default_settings)
    app.config.from_pyfile('config.py')

    if test_mode:
        # sobreescrita de conf para testing
        app.config.from_pyfile('config_testing.py')
        app.config['TESTING'] = True
        app.config['DEBUG'] = False

    # init extensions
    register_extensions(app)
    # blueprints
    regiter_bluprints(app)
    # jinja custom filters
    register_jinja_filters(app)

    app.wsgi_app = ProxyFix(app.wsgi_app)
    urls.add_url_rules(app)

    return app
Example #12
0
    def test_resource_return_values(self):
        """resource return values."""
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = Api(app)

        @api.resource('/api/<int:k>')
        class Foo(Resource):
            def get(self, k):
                if k == 0:
                    return {}, 302, {'X-Junk': 'junk header'}
                elif k == 1:
                    return api.responder(({'msg': 'no way'}, 403))

        with app.test_client() as c:
            rv = c.get('/api/0')
            assert rv.status_code == 302
            assert loads(rv.data) == {}
            assert rv.headers['X-junk'] == 'junk header'

            rv = c.get('/api/1')
            assert rv.status_code == 403
            data = loads(rv.data)
            assert data == {'msg': 'no way'}

            if app.debug is False:
                # if app.config['DEBUG'] = True you get
                # ValueError('View function did not return a response')
                rv = c.get('/api/2')
                assert rv.status_code == 500
                assert rv.headers['Content-Type'] == 'text/html'
            else:
                warnings.warn("skipping tests as flask app is DEBUG")
Example #13
0
    def test_exception_header_forwarded(self):
        """Test that HTTPException's headers are extended properly"""
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_restful.Api(app)

        class NotModified(HTTPException):
            code = 304

            def __init__(self, etag, *args, **kwargs):
                super(NotModified, self).__init__(*args, **kwargs)
                self.etag = quote_etag(etag)

            def get_headers(self, *args, **kwargs):
                """Get a list of headers."""
                return [('ETag', self.etag)]

        class Foo1(flask_restful.Resource):
            def get(self):
                flask_abort(304, etag='myETag')

        api.add_resource(Foo1, '/foo')
        _aborter.mapping.update({304: NotModified})

        with app.test_client() as client:
            foo = client.get('/foo')
            self.assertEquals(foo.get_etag(),
                              unquote_etag(quote_etag('myETag')))
Example #14
0
def create_app():
    global app
    global db
    global login_manager

    # Flask
    app = Flask(__name__)
    app.config.from_object('config.flask_config')

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Login
    login_manager = LoginManager(app)
    login_manager.login_view = 'users.login'

    # Assets
    assets = Environment(app)
    less = Bundle('less/*.less',
                  filters='less',
                  output='css/gen/style.css',
                  depends='less/*.less')
    assets.register('less_all', less)

    # Debug
    app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug')

    @login_manager.user_loader
    def load_user(userid):
        from models import User
        return User.query.get(userid)

    register_blueprints(app)
    return app, db
Example #15
0
    def test_decorator_view_response_types(self):
        """Testing decorated view responses.

        api = Api(app, decorators=[decorator_1])
        class Decorator(Resource, decorators=[decorator_2]):
            decorators = [decorator_3]

            @decorator_4
            def get(self):
                return {}

        decorator1 gets :class:`Flask.Response`
        decorator2 gets :class:`Flask.Response`
        decorator3 gets return value from Resource method
        decorator4 gets return value from Resource method
        """
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = Api(app, decorators=[add_header('x-api')])

        @api.resource('/api', decorators=[add_header('x-add')])
        class Foo(Resource):
            decorators = [add_header('x-class')]

            @add_header('x-method')
            def get(self):
                return {}

        with app.test_client() as c:
            rv = c.get('/api')
            assert rv.status_code == 200
            assert rv.headers['X-API'].startswith("<Response")
            assert rv.headers['X-ADD'].startswith("<Response")
            assert rv.headers['X-CLASS'] == "{}"
            assert rv.headers['X-METHOD'] == "{}"
Example #16
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    # Create modules
    app.register_blueprint(newsModule)
    app.register_blueprint(commentsModule)
    app.register_blueprint(weibosModule)
    app.register_blueprint(clusterModule)
    app.register_blueprint(packageModule)
    app.register_blueprint(packageWeiboModule)

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # the debug toolbar is only enabled in debug mode
    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['youremail@yourdomain.com'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'
    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'

    return app
Example #17
0
    def create_app(self):
        """Create the app."""
        from flask_iiif import IIIF
        from flask_restful import Api
        from flask_iiif.cache.simple import ImageSimpleCache

        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SERVER_NAME'] = "shield.worker.node.1"
        app.config['SITE_URL'] = "http://shield.worker.node.1"
        app.config['IIIF_CACHE_HANDLER'] = ImageSimpleCache()
        app.logger.disabled = True

        api = Api(app=app)

        iiif = IIIF(app=app)

        iiif.uuid_to_image_opener_handler(self.create_image)

        def api_decorator_test(*args, **kwargs):
            if 'decorator' in kwargs.get('uuid'):
                abort(403)

        iiif.api_decorator_handler(api_decorator_test)

        iiif.init_restful(api)
        return app
def create_app(settings=None):
    """
    Creates a flask application.

    @param settings: Settings override object.
    @return: The flask application.
    """
    app = Flask(__name__)

    if settings:
        app.config.from_object(settings)
    else:
        args = _generate_args()
        profile = args.pop('profile')
        app.config['DEBUG'] = args.pop('debug')
        config_file = _load_config_file()
        database_uri = _load_database()
        _config_from_config_profile(config_file, profile, app)
        app.config['SQLALCHEMY_DATABASE_URI'] = database_uri

    DB.init_app(app)

    default_controller = __import__(
        'ec2stack.controllers.' + 'default', None, None, 'DEFAULT'
    )
    default_controller = getattr(default_controller, 'DEFAULT')
    app.register_blueprint(default_controller)

    return app
Example #19
0
def create():
    """Create application.
    """

    # Create application
    app = Flask('service', static_folder=None)
    app.config['DEBUG'] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['SECRET_KEY'] = 'openspending rocks'
    sess.init_app(app)

    # Register blueprints
    print("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix='/datastore')
    print("Creating API Loader Blueprint")
    app.register_blueprint(apiload.create(), url_prefix='/hooks/load/')
    print("Creating Authentication Blueprint")
    app.register_blueprint(authentication.create(), url_prefix='/oauth/')
    print("Creating Authorization Blueprint")
    app.register_blueprint(authorization.create(), url_prefix='/permit/')
    print("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix='/search/')

    # Return application
    return app
Example #20
0
def create_app():
  options = {
    'port' : 0,
    'unitTesting': False
  }
  WebConfig.config(options)

  b = Borg()
  app = Flask(__name__)
  app.config['DEBUG'] = True
  app.config['SECRET_KEY'] = b.secretKey
  app.config['SECURITY_PASSWORD_HASH'] = b.passwordHash
  app.config['SECURITY_PASSWORD_SALT'] = b.passwordSalt
  app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' + b.auth_dbUser + ':' + b.auth_dbPasswd + '@' + b.auth_dbHost + '/' + b.auth_dbName
  b.logger.setLevel(b.logLevel)
  b.logger.debug('Error handlers: {0}'.format(app.error_handler_spec))
  app.secret_key = os.urandom(24)
  logger = logging.getLogger('werkzeug')
  logger.setLevel(b.logLevel)
  enable_debug = b.logLevel = logging.DEBUG

  cors = CORS(app)
  db.init_app(app)
  user_datastore = SQLAlchemyUserDatastore(db,User, Role)
  security = Security(app, user_datastore)

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

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

  return app
Example #21
0
def create_app(debug=False):
    if debug:
        print "Debug mode."
        app = Flask('wire', static_path='/static/')

    else:
        app = Flask('wire', static_path='/')

    app.config.from_object('wire.settings')
    app.config.from_envvar('WIRE_SETTINGS', silent=True)
    app.config['DEBUG'] = debug
    configure_uploads(app, uploaded_avatars)
    configure_uploads(app, uploaded_images)
    Markdown(app)

    if not debug:
        configure_logging(app)

    from wire.frontend import frontend
    app.register_blueprint(frontend, url_prefix='')

    configure_base_views(app)

    if app.config['SECRET_KEY'] == '':
        print 'Please setup a secret key in local_settings.py!!!'

    return app
Example #22
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        # Ensure that all requests have Content-Type set to "application/json"
        # unless otherwise specified.
        for methodname in ('get', 'put', 'patch', 'post', 'delete'):
            # Create a decorator for the test client request methods that adds
            # a JSON Content-Type by default if none is specified.
            def set_content_type(func):
                def new_func(*args, **kw):
                    if 'content_type' not in kw:
                        kw['content_type'] = 'application/json'
                    return func(*args, **kw)
                return new_func
            # Decorate the original test client request method.
            old_method = getattr(self.app, methodname)
            setattr(self.app, methodname, set_content_type(old_method))
Example #23
0
def create_app():

    # Create a flask app.
    app = Flask(__name__)

    # Set debug true for catching the errors.
    app.config['DEBUG'] = True

    # Set database url.
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    # Database initialize with app.
    db.init_app(app)

    # Check if there is no database.
    if not os.path.exists(SQLALCHEMY_DATABASE_URI):

        # New db app if no database.
        db.app = app

        # Create all database tables.
        db.create_all()

    # Return app.
    return app
Example #24
0
def create_app(config_name):
    
    app = Flask(__name__)
    app.config['DEBUG'] = True  
    app.config.from_object(config[config_name])
    
    '''if not app.debug and os.environ.get('HEROKU') is None:
        file_handler = RotatingFileHandler('tmp/fastmonkey.log', 'a',1 * 1024 * 1024, 10)
        file_handler.setLevel(logging.INFO)
        file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('Fastmonkey start up....')'''
    if os.environ.get('HEROKU') is not None:
        import logging
        stream_handler = logging.StreamHandler()
        app.logger.addHandler(stream_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('fastmonkey')


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

    from .fast import fast as fast_blueprint
    app.register_blueprint(fast_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)
    
    return app
Example #25
0
	def create_app():

		global db, bootstrap, mail, login_manager, moment, pagedown
		app = Flask(__name__)

		from main import main as main_blueprint
		from auth import auth as auth_blueprint
		from admin import admin as admin_blueprint

		app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://flask:gf37888676@172.17.0.25/flask'
		app.config['SQLAlCHEMY_COMMIT_ON_TEARDOWN'] = True
		app.config['FLASK_ADMIN'] = 'iamawar3player@163.com'
		app.config['FLASK_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
		app.config['FLASK_MAIL_SENDER'] = 'Flasky Admin <iamawar3player@163.com>'
		app.config['MAIL_SERVER'] = 'smtp.163.com'
		app.config['MAIL_PORT'] = 25
		app.config['MAIL_USE_TLS'] = False
		app.config['MAIL_USERNAME'] = 'iamawar3player@163.com'
		app.config['MAIL_PASSWORD'] = 'fan86797121'
		app.config['DEBUG'] = True
		app.config['FLASKY_POSTS_PER_PAGE'] = 10
		app.config['SECRET_KEY'] = 'gf37888676'
		app.register_blueprint(main_blueprint)
		app.register_blueprint(auth_blueprint, url_prefix='/auth')
		app.register_blueprint(admin_blueprint, url_prefix='/admin')

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

		return app
Example #26
0
def create_app(configfile=None):
    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patterns/appfactories/

    app = Flask(__name__)

    # We use Flask-Appconfig here, but this is not a requirement
    AppConfig(app)

    # Install our Bootstrap extension
    Bootstrap(app)

    # Our application uses blueprints as well; these go well with the
    # application factory. We already imported the blueprint, now we just need
    # to register it:
    app.register_blueprint(frontend)

    # Because we're security-conscious developers, we also hard-code disabling
    # the CDN support (this might become a default in later versions):
    app.config['BOOTSTRAP_SERVE_LOCAL'] = True
    app.config['DEBUG'] = False

    # We initialize the navigation as well
    nav.init_app(app)

    return app
Example #27
0
def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////Users/olivergoodman/Documents/github/app-blueprint/my_app/personal.db"
    db.init_app(app)    
    app.register_blueprint(hello, url_prefix='')
    return app 
Example #28
0
def create_app(config=Config()):
    """Flask application factory."""

    app = Flask(__name__)

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

    # override settings by environment variables

    if 'DEBUG' in os.environ:
        app.config['DEBUG'] = os.environ['DEBUG'].lower() == 'true'

    if 'SECRET_KEY' in os.environ:
        app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

    if 'SSL_ENABLE_REDIRECTS' in os.environ:
        app.config['SSL_ENABLE_REDIRECTS'] = os.environ['SSL_ENABLE_REDIRECTS'].lower() == 'true'

    if 'DATABASE_URL' in os.environ:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']

    db.init_app(app)
    babel = Babel(app)
    login_manager.setup_app(app)
    oid.init_app(app)
    DebugToolbarExtension(app)

    app.register_blueprint(times)

    admin = Admin(app, url_prefix='/admin', title='Admin')
    admin.add_path_security('/', secure_admin_path)
    admin.add_path_security('/auth', secure_admin_auth_path)

    auth_node = admin.register_node('/auth', 'auth', 'Authentication')
    time_node = admin.register_node('/time_node', 'time_node', 'Times')

    admin.register_module(UserAdmin, '/users', 'users', 'Users', parent=auth_node)
    admin.register_module(CompanyAdmin, '/companies', 'companies', 'Companies', parent=time_node)
    admin.register_module(ProjectAdmin, '/projects', 'projects', 'Projects', parent=time_node)
    admin.register_module(TaskAdmin, '/tasks', 'tasks', 'Tasks', parent=time_node)
    admin.register_module(WorkingUnitAdmin, '/times', 'times', 'Working Times', parent=time_node)

    @login_manager.user_loader
    def load_user(userid):
        return User.query.get(int(userid))

    @app.context_processor
    def inject_context():
        version = os.environ.get('VERSION', 'devel')
        return dict(user=current_user, now=datetime.now(), version=version)

    @babel.localeselector
    def get_locale():
        if hasattr(current_user, 'locale'):
            return current_user.locale
        return request.accept_languages.best_match(['en', 'ja', 'de'])

    return app
Example #29
0
def create_app(script_info=None):
    """Create app."""
    app = Flask(__name__)
    # logging
    if not os.path.exists(user_data_dir):
        os.makedirs(user_data_dir)
    log_dir = os.path.join(user_data_dir, 'log')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    peewee_logger = logging.getLogger('peewee')
    peewee_logger.setLevel(logging.INFO)
    chardet_logger = logging.getLogger('chardet')
    chardet_logger.setLevel(logging.INFO)
    default_log_file = os.path.join(log_dir, 'iqdb_tagger_server.log')
    file_handler = TimedRotatingFileHandler(default_log_file, 'midnight')
    file_handler.setLevel(logging.WARNING)
    file_handler.setFormatter(logging.Formatter('<%(asctime)s> <%(levelname)s> %(message)s'))
    app.logger.addHandler(file_handler)
    app.logger.addHandler(peewee_logger)
    app.logger.addHandler(chardet_logger)
    # reloader
    reloader = app.config['TEMPLATES_AUTO_RELOAD'] = \
        bool(os.getenv('IQDB_TAGGER_RELOADER')) or app.config['TEMPLATES_AUTO_RELOAD']  # NOQA
    if reloader:
        app.jinja_env.auto_reload = True
    app.config['SECRET_KEY'] = os.getenv('IQDB_TAGGER_SECRET_KEY') or os.urandom(24)
    app.config['WTF_CSRF_ENABLED'] = False
    # debug
    debug = app.config['DEBUG'] = bool(os.getenv('IQDB_TAGGER_DEBUG')) or app.config['DEBUG']
    if debug:
        app.config['DEBUG'] = True
        app.config['LOGGER_HANDLER_POLICY'] = 'debug'
        logging.basicConfig(level=logging.DEBUG)
        pprint.pprint(app.config)
        print('Log file: {}'.format(default_log_file))
        print('script info:{}'.format(script_info))
    db_path = os.getenv('IQDB_TAGGER_DB_PATH') or default_db_path
    init_program()
    init_db(db_path)
    # app and db
    app.app_context().push()

    @app.shell_context_processor
    def shell_context():  # pylint: disable=unused-variable
        return {'app': app}

    # flask-admin
    app_admin = Admin(
        app, name='IQDB Tagger', template_mode='bootstrap3',
        index_view=views.HomeView(name='Home', template='iqdb_tagger/index.html', url='/'))

    app_admin.add_view(views.MatchView())
    # app_admin.add_view(ModelView(ImageMatch, category='DB'))
    # app_admin.add_view(ModelView(ImageMatchRelationship, category='DB'))
    # app_admin.add_view(ModelView(ImageModel, category='DB'))
    # app_admin.add_view(ModelView(MatchTagRelationship, category='DB'))
    # routing
    app.add_url_rule('/thumb/<path:basename>', view_func=thumb)
    return app
Example #30
0
def create_app(app_name='web_app'):
    app = Flask(app_name)
    CORS(app)

    app.config['DEBUG'] = True
    app.register_blueprint(api)
    app.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
    return app