Python flask.has_app_context() Examples

The following are 10 code examples of flask.has_app_context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: statsd_utilities.py    From amundsenmetadatalibrary with Apache License 2.0 6 votes vote down vote up
def _get_statsd_client(*, prefix: str) -> StatsClient:
    """
    Object pool method that reuse already created StatsClient based on prefix
    :param prefix:
    :return:
    """
    if not has_app_context() or not current_app.config[config.IS_STATSD_ON]:
        return None
    else:
        if prefix not in __STATSD_POOL:
            with __STATSD_POOL_LOCK:
                if prefix not in __STATSD_POOL:
                    LOGGER.info('Instantiate StatsClient with prefix {}'.format(prefix))
                    statsd_client = StatsClient(prefix=prefix)
                    __STATSD_POOL[prefix] = statsd_client
                    return statsd_client

        if LOGGER.isEnabledFor(logging.DEBUG):
            LOGGER.debug('Reuse StatsClient with prefix {}'.format(prefix))
        return __STATSD_POOL[prefix] 
Example #2
Source File: mongodb.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_connection() -> database.Database:
    """在连接池中获得连接"""
    if not has_app_context():
        config = get_config()
        return MongoClient(**config.MONGODB).get_database(config.MONGODB_DB)
    return current_app.mongo.get_database(current_app.config['MONGODB_DB']) 
Example #3
Source File: logger.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def logger() -> SupportsLogging:
    if has_app_context(): # type: ignore
        return current_app.logger # type: ignore
    return logging # type: ignore 
Example #4
Source File: app.py    From celery-once with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def sleep_task(value):
    assert has_app_context() is True
    return sleep(value) 
Example #5
Source File: __init__.py    From contentdb with GNU General Public License v3.0 5 votes vote down vote up
def patch_task(self):
		TaskBase = self.Task
		_celery = self

		class ContextTask(TaskBase):
			abstract = True

			def __call__(self, *args, **kwargs):
				if flask.has_app_context():
					return TaskBase.__call__(self, *args, **kwargs)
				else:
					with _celery.app.app_context():
						return TaskBase.__call__(self, *args, **kwargs)

		self.Task = ContextTask 
Example #6
Source File: model.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def display_distance(self):
        if has_app_context() and g.user.is_authenticated and g.user.units:
            units = g.user.units
        else:
            units = 'local'  # default

        if units == 'local':
            country_code = (getattr(g, 'country_code', None)
                            if has_app_context()
                            else None)
            units = country_units.get(country_code, 'km_and_metres')

        return utils.display_distance(units, self.dist) 
Example #7
Source File: neo4j_proxy.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def _build_user_from_record(record: dict, manager_name: str = '') -> UserEntity:
        """
        Builds user record from Cypher query result. Other than the one defined in amundsen_common.models.user.User,
        you could add more fields from User node into the User model by specifying keys in config.USER_OTHER_KEYS
        :param record:
        :param manager_name:
        :return:
        """
        other_key_values = {}
        if has_app_context() and current_app.config[config.USER_OTHER_KEYS]:
            for k in current_app.config[config.USER_OTHER_KEYS]:
                if k in record:
                    other_key_values[k] = record[k]

        return UserEntity(email=record['email'],
                          first_name=record.get('first_name'),
                          last_name=record.get('last_name'),
                          full_name=record.get('full_name'),
                          is_active=record.get('is_active', False),
                          github_username=record.get('github_username'),
                          team_name=record.get('team_name'),
                          slack_id=record.get('slack_id'),
                          employee_type=record.get('employee_type'),
                          role_name=record.get('role_name'),
                          manager_fullname=record.get('manager_fullname', manager_name),
                          other_key_values=other_key_values) 
Example #8
Source File: celery.py    From flask-unchained with MIT License 5 votes vote down vote up
def override_task_class(self):
        BaseTask = self.Task
        _celery = self

        class ContextTask(BaseTask):
            abstract = True

            def __call__(self, *args, **kwargs):
                if flask.has_app_context():
                    return BaseTask.__call__(self, *args, **kwargs)
                else:
                    with _celery.app.app_context():
                        return BaseTask.__call__(self, *args, **kwargs)

        self.Task = ContextTask 
Example #9
Source File: celery.py    From flask-react-spa with MIT License 5 votes vote down vote up
def override_task_class(self):
        BaseTask = self.Task
        _celery = self

        class ContextTask(BaseTask):
            abstract = True

            def __call__(self, *args, **kwargs):
                if flask.has_app_context():
                    return BaseTask.__call__(self, *args, **kwargs)
                else:
                    with _celery.app.app_context():
                        return BaseTask.__call__(self, *args, **kwargs)

        self.Task = ContextTask 
Example #10
Source File: space_alert.py    From osm-wikidata with GNU General Public License v3.0 4 votes vote down vote up
def check_free_space(config=None):
    ''' Check how much disk space is free.
        E-mail admin if free space is low. '''

    if config is None:
        if not has_app_context():
            return
        config = current_app.config

    min_free_space = config.get('MIN_FREE_SPACE')

    if not min_free_space:  # not configured
        return

    free_space = utils.get_free_space(config)

    if free_space > min_free_space:
        return

    one_hour_ago = datetime.utcnow() - timedelta(hours=1)
    recent = model.SpaceWarning.most_recent()
    if recent and recent.timestamp > one_hour_ago:
        return  # already sent an alert within the last hour

    readable = humanize.naturalsize(free_space)
    subject = f'Low disk space: {readable} OSM/Wikidata matcher'

    print(f'low space warning: {readable}')

    body = f'''
Warning

The OSM/Wikidata matcher server is low on space.

There is currently {readable} available.
'''

    mail.send_mail(subject, body, config=config)

    alert = model.SpaceWarning(free_space=free_space)
    database.session.add(alert)
    database.session.commit()