flask.ctx has_request_context Example Code

has_request_context is a function within the flask.ctx module that is useful for determining if a request context is available or not. There is a similar has_app_context function as well that works for the application context.

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

Example 1 from Flask AppBuilder

Flask-AppBuilder (documentation and example apps) is a web application generator that uses Flask to automatically create the code for database-driven applications based on parameters set by the user. The generated applications include default security settings, forms, and internationalization support.

Flask App Builder is provided under the BSD 3-Clause "New" or "Revised" license.

Flask AppBuilder / flask_appbuilder / babel / manager.py

# manager.py
import os

from flask import has_request_context, request, session
from flask_babel import Babel

from .views import LocaleView
from ..basemanager import BaseManager

class BabelManager(BaseManager):

    babel = None
    locale_view = None

    def __init__(self, appbuilder):
        super(BabelManager, self).__init__(appbuilder)
        app = appbuilder.get_app
        app.config.setdefault("BABEL_DEFAULT_LOCALE", "en")
        if not app.config.get("LANGUAGES"):
            app.config["LANGUAGES"] = {"en": {"flag": "us", "name": "English"}}
        appbuilder_parent_dir = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), os.pardir
        appbuilder_translations_path = os.path.join(
            appbuilder_parent_dir, "translations"
        if "BABEL_TRANSLATION_DIRECTORIES" in app.config:
            current_translation_directories = app.config.get(
            translations_path = (
                appbuilder_translations_path + ";" + current_translation_directories
            translations_path = appbuilder_translations_path + ";translations"
        app.config["BABEL_TRANSLATION_DIRECTORIES"] = translations_path
        self.babel = Babel(app)
        self.babel.locale_selector_func = self.get_locale

    def register_views(self):
        self.locale_view = LocaleView()

    def babel_default_locale(self):
        return self.appbuilder.get_app.config["BABEL_DEFAULT_LOCALE"]

    def languages(self):
        return self.appbuilder.get_app.config["LANGUAGES"]

    def get_locale(self):
        if has_request_context():
            for arg, value in request.args.items():
                if arg == "_l_":
                    if value in self.languages:
                        return value
                        return self.babel_default_locale
            locale = session.get("locale")
            if locale:
                return locale
            session["locale"] = self.babel_default_locale
            return session["locale"]

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

Example 2 from FlaskBB

FlaskBB (project website) is a Flask-based forum web application. The web app allows users to chat in an open message board or send private messages in plain text or Markdown.

FlaskBB is provided as open source under this license.

FlaskBB / flaskbb / forum / locals.py

# locals.py

from flask import _request_ctx_stack, has_request_context, request
from werkzeug.local import LocalProxy

from .models import Category, Forum, Post, Topic

def current_post():
    return _get_item(Post, 'post_id', 'post')

def current_topic():
    if current_post:
        return current_post.topic
    return _get_item(Topic, 'topic_id', 'topic')

def current_forum():
    if current_topic:
        return current_topic.forum
    return _get_item(Forum, 'forum_id', 'forum')

def current_category():
    if current_forum:
        return current_forum.category
    return _get_item(Category, 'category_id', 'category')

def _get_item(model, view_arg, name):
    if (
        has_request_context() and
        not getattr(_request_ctx_stack.top, name, None) and
        view_arg in request.view_args

    return getattr(_request_ctx_stack.top, name, None)

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

Example 3 from Flask-SocketIO

Flask-SocketIO (PyPI package information, official tutorial and project documentation) is a code library by Miguel Grinberg that provides Socket.IO integration for Flask applications. This extension makes it easier to add bi-directional communications on the web via the WebSockets protocol.

The Flask-SocketIO project is open source under the MIT license.

Flask-SocketIO / flask_socketio / init.py

# __init__.py
from functools import wraps
import os
import sys

gevent_socketio_found = True
    from socketio import socketio_manage  # noqa: F401
except ImportError:
    gevent_socketio_found = False
if gevent_socketio_found:
    print('The gevent-socketio package is incompatible with this version of '
          'the Flask-SocketIO extension. Please uninstall it, and then '
          'install the latest version of python-socketio in its place.')

import flask
from flask import _request_ctx_stack, has_request_context, json as flask_json
from flask.sessions import SessionMixin
import socketio
from socketio.exceptions import ConnectionRefusedError  # noqa: F401
from werkzeug.debug import DebuggedApplication
from werkzeug.serving import run_with_reloader

from .namespace import Namespace
from .test_client import SocketIOTestClient

__version__ = '5.0.2dev'

class _SocketIOMiddleware(socketio.WSGIApp):
    def __init__(self, socketio_app, flask_app, socketio_path='socket.io'):
        self.flask_app = flask_app
        super(_SocketIOMiddleware, self).__init__(socketio_app,

    def __call__(self, environ, start_response):
        environ = environ.copy()
        environ['flask.app'] = self.flask_app
        return super(_SocketIOMiddleware, self).__call__(environ,

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

            def set_handler(handler):
                return self.on(handler.__name__, *args, **kwargs)(handler)

            return set_handler

    def on_namespace(self, namespace_handler):
        if not isinstance(namespace_handler, Namespace):
            raise ValueError('Not a namespace instance.')
        if self.server:

    def emit(self, event, *args, **kwargs):
        namespace = kwargs.pop('namespace', '/')
        to = kwargs.pop('to', kwargs.pop('room', None))
        include_self = kwargs.pop('include_self', True)
        skip_sid = kwargs.pop('skip_sid', None)
        if not include_self and not skip_sid:
            skip_sid = flask.request.sid
        callback = kwargs.pop('callback', None)
        if callback:
            sid = None
            if has_request_context():
                sid = getattr(flask.request, 'sid', None)
            original_callback = callback

            def _callback_wrapper(*args):
                return self._handle_event(original_callback, None, namespace,
                                          sid, *args)

            if sid:
                callback = _callback_wrapper
        self.server.emit(event, *args, namespace=namespace, to=to,
                         skip_sid=skip_sid, callback=callback, **kwargs)

    def send(self, data, json=False, namespace=None, to=None,
             callback=None, include_self=True, skip_sid=None, **kwargs):
        skip_sid = flask.request.sid if not include_self else skip_sid
        if json:
            self.emit('json', data, namespace=namespace, to=to,
                      skip_sid=skip_sid, callback=callback, **kwargs)
            self.emit('message', data, namespace=namespace, to=to,
                      skip_sid=skip_sid, callback=callback, **kwargs)

    def close_room(self, room, namespace=None):
        self.server.close_room(room, namespace)

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

Example 4 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 / core / logger.py

# logger.py

import logging
import logging.config
import logging.handlers
import os
import warnings
from pprint import pformat

import yaml
from flask import current_app, has_request_context, request, session

from indico.core.config import config
from indico.util.i18n import set_best_lang
from indico.web.util import get_request_info

    from raven import setup_logging
    from raven.contrib.celery import register_logger_signal, register_signal
    from raven.contrib.flask import Sentry
    from raven.handlers.logging import SentryHandler
except ImportError:
    Sentry = object  # so we can subclass
    has_sentry = False
    has_sentry = True

class AddRequestIDFilter:
    def filter(self, record):
        record.request_id = request.id if has_request_context() else '0' * 16
        return True

class AddUserIDFilter:
    def filter(self, record):
        record.user_id = str(session.user.id) if has_request_context() and session and session.user else '-'
        return True

class RequestInfoFormatter(logging.Formatter):
    def format(self, record):
        rv = super().format(record)
        info = get_request_info()
        if info:
            rv += '\n\n' + pformat(info)
        return rv

class FormattedSubjectSMTPHandler(logging.handlers.SMTPHandler):
    def getSubject(self, record):
        return self.subject % record.__dict__

class BlacklistFilter(logging.Filter):
    def __init__(self, names):
        self.filters = [logging.Filter(name) for name in names]

    def filter(self, record):
        return not any(x.filter(record) for x in self.filters)

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

            if formatter.pop('append_request_info', False):
                assert '()' not in formatter
                formatter['()'] = RequestInfoFormatter
        if config.DB_LOG:
            data['loggers']['indico._db'] = {'level': 'DEBUG', 'propagate': False, 'handlers': ['_db']}
            data['handlers']['_db'] = {'class': 'logging.handlers.SocketHandler', 'host': '', 'port': 9020}
            data['loggers'].setdefault('indico.customization', {})['level'] = 'DEBUG'
        if config.SENTRY_DSN:
            if not has_sentry:
                raise Exception('`raven` must be installed to use sentry logging')

    def get(cls, name=None):
        if name is None:
            name = 'indico'
        elif name != 'indico' and not name.startswith('indico.'):
            name = 'indico.' + name
        return logging.getLogger(name)

class IndicoSentry(Sentry):
    def get_user_info(self, request):
        if not has_request_context() or not session.user:
            return None
        return {'id': session.user.id,
                'email': session.user.email,
                'name': session.user.full_name}

    def before_request(self, *args, **kwargs):
        if not has_request_context():
        self.client.extra_context({'Endpoint': str(request.url_rule.endpoint) if request.url_rule else None,
                                   'Request ID': request.id})
        self.client.tags_context({'locale': set_best_lang()})

def init_sentry(app):
    sentry = IndicoSentry(wrap_wsgi=False, register_signal=True, logging=False)
    handler = SentryHandler(sentry.client, level=getattr(logging, config.SENTRY_LOGGING_LEVEL))
    handler.addFilter(BlacklistFilter({'indico.flask', 'celery.redirected'}))

def sentry_log_exception():
        sentry = current_app.extensions['sentry']
    except KeyError:

## ... source file continues with no further has_request_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