示例#1
0
 def test_set_formatter(self):
     """Test that we can override the default formatter"""
     flask_log = Logging(self.app)
     flask_log.set_formatter(TEST_FORMATTER)
     root_logger = logging.getLogger()
     # Make fake record and assert we are formatting properly
     log_record = logging.LogRecord('a', logging.CRITICAL, 'a.py', 1,
                                    'things', None, None)
     # Format should ignore message and everything, and no matter
     # what gets passed in we should just get 'stuff' back.
     for handler in root_logger.handlers:
         self.assertEqual(handler.formatter.format(log_record),
                          TEST_FORMATTER)
示例#2
0
 def test_set_formatter(self):
     """Test that we can override the default formatter"""
     flask_log = Logging(self.app)
     flask_log.set_formatter(TEST_FORMATTER)
     root_logger = logging.getLogger()
     # Make fake record and assert we are formatting properly
     log_record = logging.LogRecord(
         'a', logging.CRITICAL, 'a.py', 1, 'things', None, None
     )
     # Format should ignore message and everything, and no matter
     # what gets passed in we should just get 'stuff' back.
     for handler in root_logger.handlers:
         self.assertEqual(
             handler.formatter.format(log_record),
             TEST_FORMATTER
         )
示例#3
0
    def test_no_log_level(self):
        """
        Make sure we leave things alone if no log level is set.
        """
        self.app.config['FLASK_LOG_LEVEL'] = None
        flask_log = Logging(self.app)

        self.assertEqual(logging.NOTSET, flask_log.log_level)
示例#4
0
def create_app(config, mode):
    """ create_app::Flask.Config->binder.Mode->Flask

        Creates a Flask app and registers blueprints if any.

        config is the path to a configuration file.
        If the path to the config file is a relative path, then
        the instance folder of the app is searched. If the config file
        is located outside the app's instance folder, an absolute path
        can be used for it.
    """

    app = Flask('binder', instance_relative_config=True)

    # Add bootstrap functionality
    Bootstrap(app)

    # init flask_menu
    Menu(app)

    # Apply configuration options
    config_app(mode, config, app)

    # initialize and configure the db for use in request handlers
    config_db(db, app)

    # flask login
    setup_login_manager(app)

    # init logging
    Logging(app)

    # app error handlers
    @app.errorhandler(404)
    def error_handler(exc):
        logging.error(exc)
        return render_template('error_404.html'), 404

    @app.errorhandler(OperationalError)
    def create_db_if_not_exists(exc):
        logging.error(exc)
        db = g.get('db', None)
        if db:
            db.create_all()
        return redirect('/')

    @app.route('/favicon.ico')
    def send_favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'img/favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    # Register app blueprints
    for blueprint in BLUEPRINTS:
        app.register_blueprint(blueprint)
    return app
示例#5
0
    def test_config_log_level(self):
        """Validate that log level can be set with application"""
        root_logger = logging.getLogger()
        log_level = root_logger.level
        self.assertEqual(logging.NOTSET, log_level)

        self.app.config['FLASK_LOG_LEVEL'] = TEST_LOG_LEVEL
        Logging(self.app)
        root_logger = logging.getLogger()
        self.assertEqual(root_logger.level, getattr(logging, TEST_LOG_LEVEL))
示例#6
0
    def test_bad_log_level(self):
        """
        Set a non-existent log level and make sure we raise properly
        """
        root_logger = logging.getLogger()
        log_level = root_logger.level
        self.assertEqual(logging.NOTSET, log_level)

        self.app.config['FLASK_LOG_LEVEL'] = 'Not a real thing'
        with self.assertRaisesRegexp(ValueError, 'Invalid log level.+'):
            Logging(self.app)
示例#7
0
    def test_syslog_devices(self):
        """Test syslog address handling and handler"""
        for log_device in ['/dev/log', '/var/run/syslog', '']:
            root_logger = logging.getLogger()
            # Nuke syslog handlers from init_app
            syslog_handlers = []
            for handler in root_logger.handlers:
                if isinstance(handler, logging.handlers.SysLogHandler):
                    syslog_handlers.append(handler)
            for handler in syslog_handlers:
                root_logger.removeHandler(handler)

            real_exists = os.path.exists(log_device)

            def mock_effect(*args):
                """Contextual choice of log device."""
                # pylint: disable=cell-var-from-loop
                return args[0] == log_device

            # Call so that it will think /dev/log exists
            with mock.patch('os.path') as os_exists:
                os_exists.exists.side_effect = mock_effect
                if not real_exists and log_device != '':
                    with self.assertRaises(Exception):
                        Logging(self.app)
                else:
                    Logging(self.app)
                    syslog_handler = None
                    for handler in root_logger.handlers:
                        if isinstance(handler, logging.handlers.SysLogHandler):
                            syslog_handler = handler
                    self.assertIsNotNone(syslog_handler)
                    if log_device == '':
                        self.assertEqual(syslog_handler.address,
                                         ('127.0.0.1', 514))
                    else:
                        self.assertEqual(syslog_handler.address, log_device)
示例#8
0
from logging.handlers import RotatingFileHandler
from logging import Formatter
import config

app = Flask(__name__)
app.config.from_object('config')
app.jinja_env.globals.update(config=config)  # Config avail to Templates

db = SQLAlchemy(app)
db.engine.execute('pragma foreign_keys=on')

Breadcrumbs(app=app)

lm = LoginManager()
lm.login_view = 'login'
lm.session_protection = "basic"
lm.init_app(app)

# Create a rotating logfile for the application
handler = RotatingFileHandler(config.FLASK_LOG_LOCATION,
                              maxBytes=config.FLASK_LOG_MAXSIZE,
                              backupCount=config.FLASK_LOG_RETAIN)
handler.setFormatter(Formatter('[%(levelname)s][%(asctime)s] %(message)s'))
app.logger.addHandler(handler)

Logging(app)  # So we don't have to type app.app.logger
logger = app.logger

# Avoid circular ref, import here
from app import views, models
示例#9
0
文件: app.py 项目: gugu/secret.ly
from flask_alembic import Alembic

from .secretly.db import db
from .secretly.feed import feed
from .secretly.auth import auth

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['FLASK_LOG_LEVEL'] = 'DEBUG'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'eps-Oyb-Toj-fI'

FlaskCLI(app)
flask_log = Logging(app)
db.init_app(app)
app.cli.add_command(alembic_cli, 'db')

alembic = Alembic()
alembic.init_app(app)

app.register_blueprint(auth, url_prefix='/auth')
app.register_blueprint(feed)


@app.before_request
def before_request():
    from .secretly.models.user import User
    if session.get('user_id'):
        request.user = User.query.get(session['user_id'])
示例#10
0
from daimaduan.extensions import assets
from daimaduan.utils.filters import datetimeformat
from daimaduan.utils.filters import md
from daimaduan.utils.filters import ternary
from daimaduan.utils.filters import time_passed


# set default CONFIG to config.cfg
if not os.environ.get('CONFIG', None):
    os.environ['CONFIG'] = 'custom_settings.py'


db = MongoEngine()
login_manager = LoginManager()
flask_log = Logging()

app = Flask(__name__)
app.config.from_object('daimaduan.default_settings')
app.config.from_envvar('CONFIG')

db.init_app(app)
flask_log.init_app(app)
celery = Celery(__name__)
celery.conf.add_defaults(app.config)

from daimaduan.views.sites import site_app
from daimaduan.views.users import user_app
from daimaduan.views.pastes import paste_app
from daimaduan.views.tags import tag_app
from daimaduan.views.bookmarks import bookmark_app
示例#11
0
from daimaduan.extensions import assets
from daimaduan.utils.filters import datetimeformat
from daimaduan.utils.filters import md
from daimaduan.utils.filters import ternary
from daimaduan.utils.filters import time_passed


# set default CONFIG to config.cfg
if not os.environ.get('CONFIG', None):
    os.environ['CONFIG'] = 'custom_settings.py'


db = MongoEngine()
login_manager = LoginManager()
flask_log = Logging()

app = Flask(__name__)
app.config.from_object('daimaduan.default_settings')
app.config.from_envvar('CONFIG')

db.init_app(app)
flask_log.init_app(app)
celery = Celery(__name__)
celery.conf.add_defaults(app.config)

from daimaduan.views.sites import site_app
from daimaduan.views.users import user_app
from daimaduan.views.pastes import paste_app
from daimaduan.views.tags import tag_app
from daimaduan.views.bookmarks import bookmark_app
# flask imports
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from flask.ext.jsonschema import JsonSchema
from flask.ext.redis import FlaskRedis
from flask.ext.cors import CORS
from flask.ext.admin import Admin
from flask.ext.elasticsearch import FlaskElasticsearch
from flask.ext.log import Logging
from flask.ext.migrate import Migrate

# project imports
# from application.modules.bug_report import BugReport

db = SQLAlchemy()
cache = Cache()
json = JsonSchema()
redis = FlaskRedis()
# bug_report = BugReport()
cors = CORS()
admin = Admin(template_mode='bootstrap3', url='/admin')
es = FlaskElasticsearch()
log = Logging()
migrate = Migrate()