Beispiel #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py', silent=True)
    app.jinja_env.globals['get_resource_as_string'] = get_resource_as_string
    if app.config.get('DEBUG'):
        from flask_cors import CORS
        CORS(app)  # enable for development (allow localhost)
    FlaskJSON(app)
    Logging(app)
    Marshmallow(app)
    db = MongoEngine(app)
    swagger = Swagger(app, template=app.config.get('TEMPLATE'))
    collections = get_collections(db)

    for collection in collections:
        module_path = '.'.join(['mpcontribs', 'api', collection, 'views'])
        try:
            module = import_module(module_path)
        except ModuleNotFoundError:
            logger.warning('API module {} not found!'.format(module_path))
            continue
        try:
            blueprint = getattr(module, collection)
            app.register_blueprint(blueprint, url_prefix='/' + collection)
        except AttributeError as ex:
            logger.warning('Failed to register blueprint {}: {}'.format(
                module_path, collection, ex))

    return app
Beispiel #2
0
def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    flask_log = Logging(app)
    Bootstrap(app)
    db.init_app(app)

    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

    migrate = Migrate(app, db)
    from app import models

    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_view = "auth.login"

    # Blueprints
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .dash import dash as dash_blueprint
    app.register_blueprint(dash_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint)

    # custom error views

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html', title='Forbidden'), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('errors/404.html', title='Page Not Found'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html', title='Server Error'), 500

    return app
Beispiel #3
0
def create_app():
    from . import models, blueprints

    app = Flask(__name__)

    # Init logger
    app.config['FLASK_LOG_LEVEL'] = constants.LOG_LEVEL
    flask_log = Logging(app)

    # Init models and blueprints
    app.config['SECRET_KEY'] = secrets.FLASK_SECRET_STRING
    models.init_app(app, db, ENVIRONMENT)
    blueprints.init_app(app, [auth, main])

    # Establish login procedure
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return models.users.User.query.get(int(user_id))

    return app
Beispiel #4
0
                                skip_tables=False,
                                **kwargs):
        app = self.get_app(app)

        if bind == '__all__':
            binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ())
        elif isinstance(bind, string_types) or bind is None:
            binds = [bind]
        else:
            binds = bind

        for bind in binds:
            extra = {}
            if not skip_tables:
                tables = self.get_tables_for_bind(bind)
                extra['tables'] = tables
            op = getattr(self.Model.metadata, operation)
            op(bind=self.get_engine(app, bind), **extra)

    def reflect(self, bind='__all__', app=None, **kwargs):
        self._execute_for_all_tables(app,
                                     bind,
                                     'reflect',
                                     skip_tables=True,
                                     **kwargs)


cache = Cache()
log = Logging()
db = MySQLAlchemy()
Beispiel #5
0
def create_app():
    """create flask app"""
    app = Flask(__name__)
    app.config.from_pyfile("config.py", silent=True)
    logger.warning("database: " + app.config["MPCONTRIBS_DB"])
    app.config["USTS"] = URLSafeTimedSerializer(app.secret_key)
    app.jinja_env.globals["get_resource_as_string"] = get_resource_as_string
    app.jinja_env.lstrip_blocks = True
    app.jinja_env.trim_blocks = True

    if app.config.get("DEBUG"):
        from flask_cors import CORS

        CORS(app)  # enable for development (allow localhost)

    Compress(app)
    Logging(app)
    Marshmallow(app)
    MongoEngine(app)
    Swagger(app, template=app.config.get("TEMPLATE"))
    # NOTE: hard-code to avoid pre-generating for new deployment
    # collections = get_collections(db)
    collections = [
        "projects",
        "contributions",
        "tables",
        "structures",
        "notebooks",
    ]

    for collection in collections:
        module_path = ".".join(["mpcontribs", "api", collection, "views"])
        try:
            module = import_module(module_path)
        except ModuleNotFoundError as ex:
            logger.warning(f"API module {module_path}: {ex}")
            continue

        try:
            blueprint = getattr(module, collection)
            app.register_blueprint(blueprint, url_prefix="/" + collection)
            klass = getattr(module, collection.capitalize() + "View")
            register_class(app, klass, name=collection)
            logger.warning(f"{collection} registered")
        except AttributeError as ex:
            logger.warning(
                f"Failed to register {module_path}: {collection} {ex}")

    # TODO discover user-contributed views automatically
    # only load for main deployment
    if os.environ.get("API_PORT", "5000") == "5000":
        collection = "redox_thermo_csp"
        module_path = ".".join(["mpcontribs", "api", collection, "views"])
        try:
            module = import_module(module_path)
            blueprint = getattr(module, collection)
            app.register_blueprint(blueprint, url_prefix="/" + collection)
            logger.warning(f"{collection} registered")
        except ModuleNotFoundError as ex:
            logger.warning(f"API module {module_path}: {ex}")

    app.register_blueprint(sse, url_prefix="/stream")
    # TODO add healthcheck view/url
    logger.warning("app created.")
    return app
Beispiel #6
0
# Config defaults
app.config['FLASK_LOG_LEVEL'] = 'INFO'

# Load config from environment
for key in ['MICROTICKS_SENTRY_DSN', 'FLASK_LOG_LEVEL', 'MICROTICKS_KEY']:
    if os.environ.get(key):
        app.config.update({key: os.environ.get(key)})

if app.config.get('MICROTICKS_SENTRY_DSN') is not None:
    # Optional: Use Sentry to log errors if configured in the config file
    sentry = Sentry(app, dsn=app.config['MICROTICKS_SENTRY_DSN'])

# Middleware
FlaskJSON(app)
CORS(app)
Logging(app)

if not os.path.exists(app.instance_path):
    os.makedirs(app.instance_path)


def connect_db():
    """
    Instance path: See http://flask.pocoo.org/docs/0.12/config/#instance-folders
    """
    return Database(os.path.join(app.instance_path, 'microticks.db'))


def get_db():
    """
    Opens a new database connection if there is none yet for the
Beispiel #7
0
                   basePath=BaseURL,
                   resourcePath='/',
                   produces=["application/json"],
                   api_spec_url='/webservices/variantvalidator',
                   description='VariantValidator web API'
                   )
else:
    api = swagger.docs(Api(application), apiVersion=str(api_version),
                   resourcePath='/',
                   produces=["application/json"],
                   api_spec_url='/webservices/variantvalidator',
                   description='VariantValidator web API'
                   )

# Create Logging instance
flask_log = Logging(application)


# Resources
############
"""
Essentially web pages that display json data
"""

"""
Home
"""

class home(Resource):
    def get(self):
        root_url = str(request.url_root)
Beispiel #8
0
from flask_jwt import JWT

import xiandb as db

try:
    with open(os.path.expanduser('~') + '/xian/config.yml', 'r') as cfg_file:
        cfg = yaml.load(cfg_file)
except IOError:
    print "Couldn't find a valid configuration file in ~/xian/config.xml"
    print "Please refer to README.rst"
    raise

app = Flask(__name__)
app.config.from_pyfile('app.cfg')
api = Api(app)
flask_log = Logging(app)
app.cfg = cfg


@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = make_response(json_util.dumps(data), code)
    resp.headers.extend(headers or {})
    return resp


def authenticate(name, password):
    user = db.User.authenticate(name, password)
    if user:
        return {'id': user['_id']}
Beispiel #9
0
from maintenance_calendar import app
import maintenance_calendar.views
from maintenance_calendar import config

#inicalize the Logger of Flask
from flask_log import Logging
import logging
root_logger = logging.getLogger()

#configure rotatin handler
file_hander = logging.handlers.RotatingFileHandler(
    config.log_file,
    maxBytes=config.maxbytes_log_file,
    backupCount=config.backupCount_log_file)
root_logger.addHandler(file_hander)
#configure console handler
console_logger = logging.StreamHandler()
root_logger.addHandler(console_logger)
app.config['FLASK_LOG_LEVEL'] = config.log_level
flask_log = Logging(app)
flask_log.set_formatter(config.formatter_log)

try:
    app.run(host='0.0.0.0', port=8085, debug=True)

finally:
    logging.info("Closing the handers of the logging")
    root_logger.removeHandler(file_hander)
    file_hander.close()
    root_logger.removeHandler(console_logger)
    console_logger.close()