def init_app(self, app):
        # Ensure that the traceid is parsed/propagated on every request
        app.before_request(before_request)

        # Let's get the app's base package name so we can set the correct formatter, filter and logger names
        app_module_name = Path(__file__).resolve().parents[2].parts[-1]

        logconfig = {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "simple": {
                    "()":
                    app_module_name +
                    ".custom_extensions.enhanced_logging.formatters.JsonFormatter"
                },
                "content_security_policy": {
                    "()":
                    app_module_name + ".custom_extensions.enhanced_logging"
                    ".formatters.ContentSecurityPolicyFormatter"
                },
            },
            "filters": {
                "contextual": {
                    "()":
                    app_module_name +
                    ".custom_extensions.enhanced_logging.filters.ContextualFilter"
                }
            },
            "handlers": {
                "console": {
                    "class": "logging.StreamHandler",
                    "formatter": "simple",
                    "filters": ["contextual"],
                    "stream": "ext://sys.stdout",
                },
                "content_security_policy": {
                    "class": "logging.StreamHandler",
                    "formatter": "content_security_policy",
                    "filters": ["contextual"],
                    "stream": "ext://sys.stdout",
                },
            },
            "loggers": {
                app.logger.name: {
                    "handlers": ["console"],
                    "level": app.config["FLASK_LOG_LEVEL"]
                },
                "content_security_policy": {
                    "handlers": ["content_security_policy"],
                    "level": app.config["FLASK_LOG_LEVEL"],
                },
            },
        }

        app.config.update(LOGCONFIG=logconfig)

        logger = LogConfig()

        logger.init_app(app)
Beispiel #2
0
    def init_app(self, app):
        # Ensure that the traceid is parsed/propagated on every request
        app.before_request(before_request)

        # Let's get the app's base package name so we can set the correct formatter, filter and logger names
        app_module_name = Path(__file__).resolve().parents[2].parts[-1]

        logconfig = {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'simple': {
                    '()': app_module_name + '.custom_extensions.enhanced_logging.formatters.JsonFormatter'
                },
                'content_security_policy': {
                    '()': app_module_name + '.custom_extensions.enhanced_logging'
                                            '.formatters.ContentSecurityPolicyFormatter'
                }
            },
            'filters': {
                'contextual': {
                    '()': app_module_name + '.custom_extensions.enhanced_logging.filters.ContextualFilter'
                }
            },
            'handlers': {
                'console': {
                    'class': 'logging.StreamHandler',
                    'formatter': 'simple',
                    'filters': ['contextual'],
                    'stream': 'ext://sys.stdout'
                },
                'content_security_policy': {
                    'class': 'logging.StreamHandler',
                    'formatter': 'content_security_policy',
                    'filters': ['contextual'],
                    'stream': 'ext://sys.stdout'
                }
            },
            'loggers': {
                app.logger.name: {
                    'handlers': ['console'],
                    'level': app.config['FLASK_LOG_LEVEL']
                },
                'content_security_policy': {
                    'handlers': ['content_security_policy'],
                    'level': app.config['FLASK_LOG_LEVEL']
                }

            }
        }

        app.config.update(LOGCONFIG=logconfig)

        logger = LogConfig()

        logger.init_app(app)
Beispiel #3
0
def make_app(**extra_config):
    app = Flask(__name__, static_folder='static', template_folder='templates')
    app.config.from_object('f2e.default_config')
    for k in app.config:
        value_from_env = os.getenv(k)
        if value_from_env is None:
            continue
        app.config[k] = value_from_env
    app.config.update(extra_config)
    logcfg = LogConfig()
    logcfg.init_app(app)

    app.twilio_client = TwilioRestClient(app.config['TWILIO_ACCOUNT_SID'],
                                         app.config['TWILIO_AUTH_TOKEN'])
    app.twilio_download_session = requests.Session()
    retries = Retry(total=3,
                    backoff_factor=1,
                    status_forcelist=[404, 502, 503, 504])
    app.twilio_download_session.auth = (app.config['TWILIO_ACCOUNT_SID'],
                                        app.config['TWILIO_AUTH_TOKEN'])
    app.twilio_download_session.mount('http://',
                                      HTTPAdapter(max_retries=retries))
    app.twilio_download_session.mount('https://',
                                      HTTPAdapter(max_retries=retries))
    app.sendgrid_client = SendGridAPIClient(
        apikey=app.config['SENDGRID_API_KEY'])
    app.pdf = pdf.PDFKit(app.config)

    logging.info('Mounting twilio directory')
    app.register_blueprint(bp_twilio.mod, url_prefix='/twilio')

    logging.info('Mounting sendgrid directory')
    app.register_blueprint(bp_sg.mod, url_prefix='/sg')

    if util.truthish(app.config['SECURE']):
        log.info('Only accepting https')

        @app.before_request
        def before_request():
            proto = request.headers.get('X-Forwarded-Proto', 'http')
            if proto == 'https':
                return
            if request.url.startswith('http://'):
                log.info('*** redirect url %s => https', request.url)
                log.info('... request headers follow')
                for k, v in request.headers.items():
                    log.info('... %20s => %r', k, v)
                url = request.url.replace('http://', 'https://', 1)
                return redirect(url, 301)

    return app
from flask_logconfig import LogConfig
import logging
import json
import traceback
from flask import g, ctx, request
from validation_api.validation.schema_extension import SchemaExtension
import collections

# Create empty extension objects here
logger = LogConfig()
schema_extension = SchemaExtension()


def register_extensions(app):
    """Adds any previously created extension objects into the app, and does any further setup they need."""
    # Logging
    logger.init_app(app)

    # Along with the default flask logger (app.logger) define a new one specifically for audit. To use this logger
    # just add app.audit_logger.info("an audit point").
    app.audit_logger = logging.getLogger("audit")

    schema_extension.init_app(app)

    # All done!
    app.logger.info("Extensions registered")


class ContextualFilter(logging.Filter):
    def filter(self, log_record):
        """Provide some extra variables to be placed into the log message"""
from apps.flask_jwt_extended import JWTManager
from flask_bcrypt import Bcrypt
from flask_logconfig import LogConfig
from flask_cors import CORS

bcrypt = Bcrypt()

# db =

# 日志
logcfg = LogConfig()

# jwt
jwt = JWTManager()

# csrf跨域
cors = CORS()
#!/usr/bin/env python
# encoding: utf-8
"""
@author: LiuZhi
@contact: [email protected]
@software: PyCharm
@file: extensions.py
@time: 2018-12-22 23:25
Extensions module. Each extension is initialized in the app factory located in app.py
"""

from flask_debugtoolbar import DebugToolbarExtension
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect
from flask_logconfig import LogConfig
from flask_mail import Mail

# 可先创建实例,通过self.init_app方法完成初始化(using lazy instantiation)

csrf_protect = CSRFProtect()
login_manager = LoginManager()
debug_toolbar = DebugToolbarExtension()
# webpack = Webpack()
log_cfg = LogConfig()  # LOG
mail = Mail()
def init_app(app, settings):
    app.config.from_object(settings)
    logcfg = LogConfig()
    logcfg.init_app(app)
    return logcfg
Beispiel #8
0
def init_app(app, settings):
    app.config.from_object(settings)
    logcfg = LogConfig()
    logcfg.init_app(app)
    return logcfg
Beispiel #9
0
from flask_logconfig import LogConfig
from flask_jwt_extended import JWTManager

from apis.hello import Hello

app = Flask(__name__)

# App configs
app.config.from_pyfile('configs/app.default.py')
CONFIG_ENVVAR = 'APP_CONF'
if CONFIG_ENVVAR in os.environ.keys():
    app.config.from_envvar(CONFIG_ENVVAR, silent=True)

# Modifiers
CORS(app)
LogConfig(app)
JWTManager(app)

# Add flask_restful endpoints
api = Api(app)
api.add_resource(Hello, '/hello')

logger = logging.getLogger('app')


def on_exit():
    pass


atexit.register(on_exit)
Beispiel #10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config["SQLALCHEMY_ECHO"] = True

    config[config_name].init_app(app)
    # flask 后台自定义后台管理
    admin = Admin(app, name='pim_admin', template_mode='bootstrap2')
    db.init_app(app)
    douwa.init_app(app)
    LogConfig(app)
    redis.connect(app.config["REDIS_HOST"], app.config["REDIS_PORT"],
                  app.config["REDIS_DB"])

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from app.models import PimTask, PimClothInfo, PimDefect, PimDefectType, PimLeave, PimLeaveReceiver, \
        PimLeaveType, PimLeaveWorkHandType, PimLocationType, PimReport, PimSaveInputInfo, PimSize

    from app.models import LooseInfo, InputLoose

    class PimTaskModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('location', 'volu_num', 'work_status')

    class PimClothInfoModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('order_num', 'cloth_num', 'species_name')

    class PimDefectModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        form_columns = [
            'user_id', 'length', 'defect_type', 'location', 'size', 'points',
            'spec', 'extend', 'code_number'
        ]
        column_searchable_list = ('user_id', 'length')

    class PimDefectTypeModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('defect_name', )

    class PimLeaveModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        form_columns = [
            'user_id', 'leave_reason', 'start_time', 'end_time', 'work_hand',
            'receiver', 'leave_type', 'num_day', 'spec', 'extend', 'result'
        ]
        column_searchable_list = ('user_id', 'leave_reason')

    class PimLeaveReceiverModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        form_columns = ['leave_receiver_name', 'user_id']
        column_searchable_list = ('user_id', 'leave_receiver_name')

    class PimLeaveTypeModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        form_columns = ['leave_type', 'user_id']

        column_searchable_list = ('user_id', 'leave_type')

    class PimLeaveWorkHandTypeModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        form_columns = ['work_hang_type', 'user_id']

        column_searchable_list = ('user_id', 'work_hang_type')

    class PimLocationTypeModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'position_name')

    class PimReportModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'report_type', 'date_time')

    class PimSaveInputInfoModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'code_number')

    class PimSizeModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'size_name')

    class LooseInfoModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'code_number')

    class InputLooseModelView(ModelView):
        can_delete = False  # disable model deletion
        page_size = 5  # the number of entries to display on the list view
        column_searchable_list = ('user_id', 'code_number')

    admin.add_view(PimTaskModelView(PimTask, db.session))
    admin.add_view(PimClothInfoModelView(PimClothInfo, db.session))
    admin.add_view(PimDefectModelView(PimDefect, db.session))
    admin.add_view(PimDefectTypeModelView(PimDefectType, db.session))
    admin.add_view(PimLeaveModelView(PimLeave, db.session))
    admin.add_view(PimLeaveReceiverModelView(PimLeaveReceiver, db.session))
    admin.add_view(PimLeaveTypeModelView(PimLeaveType, db.session))
    admin.add_view(
        PimLeaveWorkHandTypeModelView(PimLeaveWorkHandType, db.session))
    admin.add_view(PimLocationTypeModelView(PimLocationType, db.session))
    admin.add_view(PimReportModelView(PimReport, db.session))
    admin.add_view(PimSaveInputInfoModelView(PimSaveInputInfo, db.session))
    admin.add_view(PimSizeModelView(PimSize, db.session))
    admin.add_view(LooseInfoModelView(LooseInfo, db.session))
    admin.add_view(InputLooseModelView(InputLoose, db.session))

    return app