Пример #1
0
    def init_app(self, app):
        assert self.STATE_KEY not in app.extensions
        app.extensions[self.STATE_KEY] = HealthTester(self.configs)
        app.before_request(self.before_request)
        request_finished.connect(self.handle_request_finished, app)
        request_tearing_down.connect(self.handle_request_tearing_down, app)
        got_request_exception.connect(self.handle_got_request_exception, app)

        from huskar_api.models.signals import session_load_user_failed
        session_load_user_failed.connect(self.handle_load_user_failed)
Пример #2
0
def connect_signals(app):
    appcontext_popped.connect(handle_appcontext_popped)
    appcontext_pushed.connect(handle_appcontext_pushed)
    appcontext_tearing_down.connect(handle_appcontext_tearing_down)

    before_render_template.connect(handle_before_render_template, app)
    got_request_exception.connect(handle_got_request_exception, app)

    request_finished.connect(handle_request_finished, app)
    request_started.connect(handle_request_started, sender=app, weak=True)
    request_tearing_down.connect(handle_request_tearing_down, app, False)

    template_rendered.connect(handle_template_rendered, sender=app)
Пример #3
0
    def init_app(self, app, context_generators={}, report_exceptions=False):
        """
        Initialize honeybadger and listen for errors
        :param app: the Flask application object.
        :param context_generators: a dictionary with key the name of additional context property to add and value a
        callable that generates the actual value of the property.
        :param bool report_exceptions: whether to automatically report exceptions on requests or not.
        """
        self.context_generators = context_generators
        self.report_exceptions = report_exceptions
        self.initialize_honeybadger(app.config)
        self._patch_generic_request_payload()
        self.skip_headers = set(csv_to_list(app.config.get('HONEYBADGER_EXCLUDE_HEADERS', DEFAULT_SKIP_HEADERS)))
        request_started.connect(self.setup_context, sender=app, weak=False)
        request_tearing_down.connect(self.reset_context, sender=app, weak=False)
        logger.info('Honeybadger Flask helper installed')

        if self.report_exceptions:
            logger.info('Enabling auto-reporting exceptions')
            got_request_exception.connect(self._handle_exception, sender=app, weak=False)
Пример #4
0
def mdk_setup(app, timeout=None, mdk=None):
    """
    Setup MDK integration with Flask.

    :param app: A Flask application instance.
    :param timeout: Default timeout in seconds to set for the MDK session.
    :param mdk: An optional ``mdk.MDK`` instance to use instead of creating a
        new one. It will not be started or stopped.

    :return: The ``mdk.MDK`` instance.
    """
    if mdk is None:
        app.mdk = start()
        atexit.register(app.mdk.stop)
    else:
        app.mdk = mdk
    if timeout is not None:
        app.mdk.setDefaultDeadline(timeout)
    request_started.connect(_on_request_started, app)
    got_request_exception.connect(_on_request_exception, app)
    request_tearing_down.connect(_on_request_tearing_down, app)
    return app.mdk
Пример #5
0
def create_app(testing=False):
    application = Flask(__name__, static_folder='jarr/static',
                        template_folder='../templates')

    CORS(application, resources={r"/*": {"origins": "*"}})
    if testing:
        application.debug = True
        application.config['TESTING'] = True
        application.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
    else:
        application.debug = conf.log.level <= logging.DEBUG
    application.config['PREFERRED_URL_SCHEME'] = conf.api.scheme
    application.config['RESTX_JSON'] = {'default': default_handler}
    if conf.api.server_name:
        application.config['SERVER_NAME'] = conf.api.server_name

    api = setup_api(application)
    setup_jwt(application, api)

    request_tearing_down.connect(commit_pending_sql, application)
    got_request_exception.connect(rollback_pending_sql, application)
    return application
Пример #6
0
def create_app(object_name):
    app = Flask(__name__, template_folder='templates')

    # here = os.path.abspath(os.path.dirname(__file__))

    if os.path.exists('dev'):
        app.config.from_object(DevConfig)
    else:
        app.config.from_object(ProdConfig)

    eventlet.monkey_patch()
    mako.init_app(app)
    db.init_app(app)
    hashing.init_app(app)
    admin.init_app(app)
    login_manager.init_app(app)
    # csrf.init_app(app)
    debug_toolbar.init_app(app)
    cache.init_app(app)

    SOCKETIO_REDIS_URL = app.config['CELERY_BACKEND_URL']
    socketio.init_app(app,
                      async_mode='eventlet',
                      message_queue=SOCKETIO_REDIS_URL)

    # celery = Celery(app.name)
    # celery.conf.update(app.config)

    api.init_app(app)

    admin.add_view(CustomView(name='Custom'))
    show_models = [
        YjStationInfo, YjPLCInfo, YjGroupInfo, YjVariableInfo, Value,
        TransferLog, User
    ]

    for model in show_models:
        admin.add_view(CustomModelView(model, db.session, category='models'))
    admin.add_view(
        CustomFileAdmin(os.path.join(os.path.dirname(__file__), 'static'),
                        '/static/',
                        name='Static File'))

    def get_current_user():
        return session['username']

    @app.errorhandler(500)
    def server_inner_error(error):
        return u"内部代码错误 by yakumo17s"

    def close_db_connection(sender, **extra):
        db.session.close()
        # sender.logger.debug('Database close.')

    request_tearing_down.connect(close_db_connection, app)

    @app.context_processor
    def template_extras():
        return {'enumerate': enumerate, 'current_user': current_user}

    @app.template_filter('capitalize')
    def reverse_filter(s):
        return s.capitalize()

    @user_logged_in.connect_via(app)
    def _track_logins(sender, user, **extra):
        # 记录用户登录次数,登录IP
        user.login_count += 1
        user.last_login_ip = request.remote_addr
        user.last_login_time = int(time.time())
        db.session.add(user)
        db.session.commit()

    @login_manager.user_loader
    def user_loader(user_id):
        user = User.query.get(user_id)
        return user

    def _get_frame(date_string):
        db = MySQLdb.connect('localhost', 'web', 'web', 'pyplc')
        query = 'SELECT * FROM {}'.format(date_string)
        df = read_sql(query, db)
        df = df.head(100)
        return df

    @app.route(
        '/db/<any(yjstationinfo, yjplcinfo, yjgroupinfo, yjvariableinfo):date_string>/'
    )
    @cache.cached(timeout=10)
    def show_tables(date_string=None):
        df = _get_frame(date_string)
        if isinstance(df, bool) and not df:
            return 'Bad data format!'
        return render_template('show_data.html',
                               df=df.to_html(classes='frame'),
                               date_string=date_string)

    app.register_blueprint(basic_blueprint)
    app.register_blueprint(api_blueprint)
    app.register_blueprint(client_blueprint)
    return app
Пример #7
0
# 在响应发送给客户端之前发送
def log_response(sender, response, **extra):
    sender.logger.debug('Request context is about to close down. Response: %s', response)

from flask import request_finished
request_finished.connect(log_response, app)

# 4. flask.got_request_exception
# 在请求处理中抛出异常时发送, 异常本身通过exception传递到订阅函数
def log_exception(sender, exception, **extra):
    sender.logger.debug('Got exception during processing: %s', exception)

from flask import got_request_exception
got_requset_exception.connect(log_exception, app)

# 5. flask.request_tearing_down
# 在请求销毁时发送
def close_db_connection(sender, extra):
    session.close()

from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)

# 6. flask.appcontext_tearing_down
# 在应用上下文销毁时发送
def close_db_connection(sender, **extra):
    session.close()

from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, app)
Пример #8
0

if 'TEST_DATA_ROOT' in os.environ:
    TEST_DATA_ROOT = os.environ['TEST_DATA_ROOT']
    STATIC_FOLDER = os.path.join(u'..', TEST_DATA_ROOT, u'assets')
    TEMPLATE_FOLDER = os.path.join(u'..', TEST_DATA_ROOT, u'templates')
    app = Flask(__name__,
                static_folder=os.path.join(u'..', TEST_DATA_ROOT, u'assets'),
                template_folder=os.path.join(u'..', TEST_DATA_ROOT, u'templates')
                )
else:
    app = Flask(__name__, static_folder='assets')

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

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True


from website.site import Site
site = Site()

import website.route
import website.filter

# load cached resources on each request if they are outdated
request_started.connect(site.load_menus, app)

# flush request error messages after request
request_tearing_down.connect(site.flush_errors, app)
Пример #9
0
 def init_flask_structlog(self, app):
     request_started.connect(log_request_info, app)
     request_tearing_down.connect(remove_request_logging, app)
Пример #10
0
def create_app():
    app = Flask(__name__, template_folder='templates')

    # here = os.path.abspath(os.path.dirname(__file__))
    # 判断调用开发或生产环境配置
    if platform.system() == 'Darwin':
        app.config.from_object(DevConfig)
    else:
        app.config.from_object(ProdConfig)

    # eventlet.monkey_patch()
    mako.init_app(app)
    db.init_app(app)
    # with app.app_context():
    #     db.create_all()
    hashing.init_app(app)
    # admin.init_app(app)
    login_manager.init_app(app)
    # csrf.init_app(app)
    debug_toolbar.init_app(app)
    # cache.init_app(app)

    # SOCKETIO_REDIS_URL = app.config['CELERY_BACKEND_URL']
    # socketio.init_app(
    #     app, async_mode='eventlet',
    #     message_queue=SOCKETIO_REDIS_URL
    # )

    # celery = Celery(app.name)
    # celery.conf.update(app.config)

    api.init_app(app)

    # admin.add_view(CustomView(name='Custom'))
    # show_models = [YjStationInfo, YjPLCInfo, YjGroupInfo, YjVariableInfo, Value, TransferLog, User]
    #
    # for model in show_models:
    #     admin.add_view(
    #         CustomModelView(model, db.session,
    #                         category='models')
    #     )
    # admin.add_view(CustomFileAdmin(os.path.join(os.path.dirname(__file__), 'static'),
    #                                '/static/',
    #                                name='Static File'))

    def get_current_user():
        return session['username']

    # @app.errorhandler(500)
    # def server_inner_error(error):
    #     return u"内部代码错误 by yakumo17s"

    def close_db_connection(sender, **extra):
        db.session.close()
        # sender.logger.debug('Database close.')

    request_tearing_down.connect(close_db_connection, app)

    @app.context_processor
    def template_extras():
        return {'enumerate': enumerate, 'current_user': current_user}

    @app.template_filter('capitalize')
    def reverse_filter(s):
        return s.capitalize()

    @user_logged_in.connect_via(app)
    def _track_logins(sender, user, **extra):
        # 记录用户登录次数,登录IP
        user.login_count += 1
        user.last_login_ip = request.remote_addr
        user.last_login_time = int(time.time())
        db.session.add(user)
        db.session.commit()

    @login_manager.user_loader
    def user_loader(user_id):
        user = User.query.get(user_id)
        return user

    @app.teardown_appcontext
    def shutdown_session(response_or_exc):
        if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
            if response_or_exc is None:
                db.session.commit()

        db.session.remove()
        return response_or_exc

    # 注册蓝图
    app.register_blueprint(basic_blueprint)
    app.register_blueprint(api_blueprint)
    app.register_blueprint(client_blueprint)
    app.register_blueprint(task_blueprint)

    return app