flask.ctx has_app_context Example Code

has_app_context is a function in the flask.ctx module that is similar to has_request_context but for the application context rather than the request.

after_this_request and has_request_context are a couple of other callables within the flask.ctx package that also have code examples.

Example 1 from flask-restx

Flask RESTX is an extension that makes it easier to build RESTful APIs into your applications. Flask RESTX aims for minimal configuration to get basic APIs running for existing applications and it exposes endpoint documentation using Swagger.

Flask RESTX is provided as open source under the BSD 3-Clause license.

flask-restx / flask_restx / marshalling.py

# marshalling.py
from __future__ import unicode_literals

from collections import OrderedDict
from functools import wraps
from six import iteritems

from flask import request, current_app, has_app_context

from .mask import Mask, apply as apply_mask
from .utils import unpack

def make(cls):
    if isinstance(cls, type):
        return cls()
    return cls

def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=False):
    out, has_wildcards = _marshal(data, fields, envelope, skip_none, mask, ordered)

    if has_wildcards:
        from .fields import Wildcard

        items = []
        keys = []
        for dkey, val in fields.items():
            key = dkey
            if isinstance(val, dict):
                value = marshal(data, val, skip_none=skip_none, ordered=ordered)

## ... source file abbreviated to get to has_app_context examples ...

    out = OrderedDict(items) if ordered else dict(items)

    if envelope:
        out = OrderedDict([(envelope, out)]) if ordered else {envelope: out}

    return out, has_wildcards["present"]

class marshal_with(object):

    def __init__(
        self, fields, envelope=None, skip_none=False, mask=None, ordered=False
        self.fields = fields
        self.envelope = envelope
        self.skip_none = skip_none
        self.ordered = ordered
        self.mask = Mask(mask, skip=True)

    def __call__(self, f):
        def wrapper(*args, **kwargs):
            resp = f(*args, **kwargs)
            mask = self.mask
            if has_app_context():
                mask_header = current_app.config["RESTX_MASK_HEADER"]
                mask = request.headers.get(mask_header) or mask
            if isinstance(resp, tuple):
                data, code, headers = unpack(resp)
                return (
                return marshal(
                    resp, self.fields, self.envelope, self.skip_none, mask, self.ordered

        return wrapper

## ... source file continues with no further has_app_context examples...

Example 2 from indico

indico (project website, documentation and sandbox demo) is a Flask-based web app for event management. The code is open sourced under the MIT license.

indico / indico / util / i18n.py

# i18n.py

import ast
import re
from contextlib import contextmanager

from babel import negotiate_locale
from babel.core import LOCALE_ALIASES, Locale
from babel.messages.pofile import read_po
from babel.support import NullTranslations
from flask import current_app, g, has_app_context, has_request_context, request, session
from flask_babelex import Babel, Domain, get_domain
from flask_pluginengine import current_plugin
from speaklater import is_lazy_string, make_lazy_string
from werkzeug.utils import cached_property

from indico.core.config import config
from indico.util.caching import memoize_request

RE_TR_FUNCTION = re.compile(r'''_\("([^"]*)"\)|_\('([^']*)'\)''', re.DOTALL | re.MULTILINE)

babel = Babel()
_use_context = object()

def get_translation_domain(plugin_name=_use_context):
    if plugin_name is None:
        return get_domain()
        plugin = None
        if has_app_context():
            from indico.core.plugins import plugin_engine
            plugin = plugin_engine.get_plugin(plugin_name) if plugin_name is not _use_context else current_plugin
        if plugin:
            return plugin.translation_domain
            return get_domain()

def _indico_gettext(*args, **kwargs):
    func_name = kwargs.pop('func_name', 'gettext')
    plugin_name = kwargs.pop('plugin_name', None)

    translations = get_translation_domain(plugin_name).get_translations()
    return getattr(translations, func_name)(*args, **kwargs)

def lazy_gettext(string, plugin_name=None):
    if is_lazy_string(string):
        return string
    return make_lazy_string(_indico_gettext, string, plugin_name=plugin_name)

def orig_string(lazy_string):
    return lazy_string._args[0] if is_lazy_string(lazy_string) else lazy_string

## ... source file continues with no further has_app_context examples...

Sponsored By

Sentry logo

Software errors are inevitable. Chaos is not. Try Sentry for free.

AssemblyAI logo

The most accurate speech-to-text API. Built for Python developers.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2021