Python flask.current_app.app_context() Examples

The following are 18 code examples of flask.current_app.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.current_app , or try the search function .
Example #1
Source File: test_middleware.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def test_template_filters():
    template = """
        Dollar: {{ 0.1 | dollar }}<br>
        Sum Key: {{ data | sum_key('col') }}<br>
        Max Key: {{ data | max_key('col') }}<br>
        Average Key: {{ data | average_key('col') }}<br>
    """

    data = [
        dict(col=0),
        dict(col=0.5),
        dict(col=0.5),
        dict(col=1),
    ]

    with current_app.app_context():
        html = render_template_string(template, data=data)

    assert 'Dollar: $0.10<br>' in html
    assert 'Sum Key: 2.0<br>' in html
    assert 'Max Key: 1<br>' in html
    assert 'Average Key: 0.5<br>' in html 
Example #2
Source File: conftest.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def test_client():
    flask_app = create_app()

    # Flask provides a way to test your application by exposing the Werkzeug test Client
    # and handling the context locals for you.
    testing_client = flask_app.test_client()

    # Establish an application context before running the tests.
    ctx = flask_app.app_context()
    ctx.push()

    from flask import g
    g.pending_transactions = []
    g.executor_jobs = []

    yield testing_client  # this is where the testing happens!

    ctx.pop() 
Example #3
Source File: conftest.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def init_database():
    # Create the database and the database table

    with current_app.app_context():
        db.create_all()

    yield db  # this is where the testing happens!

    with current_app.app_context():
        try:
            db.session.execute('DROP MATERIALIZED VIEW IF EXISTS search_view;')
            db.session.commit()
        except:
            pass
        db.session.remove()  # DO NOT DELETE THIS LINE. We need to close sessions before dropping tables.
        db.drop_all() 
Example #4
Source File: models.py    From kqueen with MIT License 5 votes vote down vote up
def save(self, check_status=True, **kwargs):
        # While used in async method, app context is not available by default
        # and needs to be imported
        from flask import current_app as app
        from kqueen.server import create_app
        try:
            if not app.testing:
                app = create_app()
        except RuntimeError:
            app = create_app()

        with app.app_context():
            if check_status:
                self.state = self.engine_status(save=False)
            self.verbose_name = getattr(self.get_engine_cls(), 'verbose_name', self.engine)
            return super().save(**kwargs)


#
# AUTHENTICATION
# 
Example #5
Source File: tracer.py    From pyms with GNU General Public License v3.0 5 votes vote down vote up
def inject_span_in_headers(headers):
    if has_request_context():
        # FLASK https://github.com/opentracing-contrib/python-flask
        tracer = current_app.tracer if getattr(current_app, "tracer") else None
        # Add traces
        span = None
        current_app.app_context()
        if tracer:
            span = tracer.get_span(request=request)
            if not span:  # pragma: no cover
                span = get_current_span()
                if not span:
                    span = tracer.tracer.start_span()
            context = span.context if span else None
            tracer.tracer.inject(context, opentracing.Format.HTTP_HEADERS, headers)
    return headers 
Example #6
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def plugin(plugin):
    if request.method == "GET":
        plugins_path = os.path.join(app.root_path, "plugins")

        config_html_plugins = [
            name
            for name in os.listdir(plugins_path)
            if os.path.isfile(os.path.join(plugins_path, name, "config.html"))
        ]

        if plugin in config_html_plugins:
            config_html = open(
                os.path.join(app.root_path, "plugins", plugin, "config.html")
            ).read()
            return render_template_string(config_html)
        abort(404)
    elif request.method == "POST":
        for k, v in request.form.items():
            if k == "nonce":
                continue
            set_config(k, v)
        with app.app_context():
            clear_config()
        return "1" 
Example #7
Source File: execute_task.py    From freight with Apache License 2.0 5 votes vote down vote up
def start(self):
        # TODO(dcramer): we should probably move the log capture up to this
        # level so we *always* get full/correct logs
        assert not self.active, "TaskRunner already started"
        self.active = True
        self._started = time()
        self._process = Popen(
            args=["bin/run-task", str(self.task.id)],
            cwd=PROJECT_ROOT,
            stdout=PIPE,
            stderr=STDOUT,
        )
        self._logreporter = LogReporter(
            app_context=current_app.app_context(),
            task_id=self.task.id,
            process=self._process,
        )
        self._logreporter.start()

    # TODO(dcramer): currently this is the sum of checks + job time which
    # isnt ideal. We either could move checks into execute_task and have a new
    # timeout just for them, or assume this timeout includes both and likely
    # still add another timeout for checks 
Example #8
Source File: api.py    From NaturewatchCameraServer with GNU General Public License v3.0 4 votes vote down vote up
def feed():
    """
    Feed endpoint
    :return: mjpg content
    """
    current_app.logger.info("Serving camera feed...")
    with current_app.app_context():
        return Response(generate_mjpg(current_app.camera_controller),
                        mimetype='multipart/x-mixed-replace; boundary=frame') 
Example #9
Source File: email.py    From picoCTF with MIT License 4 votes vote down vote up
def refresh_email_settings():
    """
    Load the current app context mail settings.

    Called to make sure that the current thread/worker has the newest
    email settings from the database.
    """
    with current_app.app_context():
        settings = api.config.get_settings()
        if settings["email"]["enable_email"]:
            current_app.config["MAIL_SUPPRESS_SEND"] = False
            current_app.config["MAIL_SERVER"] = settings["email"]["smtp_url"]
            current_app.config["MAIL_PORT"] = settings["email"]["smtp_port"]
            current_app.config["MAIL_USERNAME"] = settings["email"]["email_username"]
            current_app.config["MAIL_PASSWORD"] = settings["email"]["email_password"]
            current_app.config["MAIL_DEFAULT_SENDER"] = settings["email"]["from_addr"]
            if settings["email"]["smtp_security"] == "TLS":
                current_app.config["MAIL_USE_TLS"] = True
                current_app.config["MAIL_USE_SSL"] = False
            elif settings["email"]["smtp_security"] == "SSL":
                current_app.config["MAIL_USE_TLS"] = False
                current_app.config["MAIL_USE_SSL"] = True
        else:
            # Use a testing configuration
            current_app.config["MAIL_SUPPRESS_SEND"] = True
            current_app.config["MAIL_DEFAULT_SENDER"] = "testing@picoctf.com"
    mail.init_app(current_app) 
Example #10
Source File: models.py    From kqueen with MIT License 4 votes vote down vote up
def save(self, **kwargs):
        # While used in async method, app context is not available by default
        # and needs to be imported
        from flask import current_app as app
        from kqueen.server import create_app

        try:
            if not app.testing:
                app = create_app()
        except RuntimeError:
            app = create_app()

        with app.app_context():
            return super().save(**kwargs) 
Example #11
Source File: sessions.py    From amivapi with GNU Affero General Public License v3.0 4 votes vote down vote up
def delete_expired_sessions():
    """Delete expired sessions.

    Needs an app context to access current_app,
    make sure to create one if necessary.

    E.g.
    >>> with app.app_context():
    >>>     delete_expired_sessions()
    """
    deadline = datetime.datetime.utcnow() - app.config['SESSION_TIMEOUT']
    app.data.driver.db['sessions'].delete_many({'_updated': {'$lt': deadline}}) 
Example #12
Source File: autodoc.py    From syntheticmass with Apache License 2.0 4 votes vote down vote up
def html(self, groups='all', template=None, **context):
        """Return an html string of the routes specified by the doc() method

        A template can be specified. A list of routes is available under the
        'autodoc' value (refer to the documentation for the generate() for a
        description of available values). If no template is specified, a
        default template is used.

        By specifying the group or groups arguments, only routes belonging to
        those groups will be returned.
        """
        if template:
            return render_template(template,
                                   autodoc=self.generate(groups=groups),
                                   **context)
        else:
            filename = os.path.join(
                os.path.dirname(__file__),
                'templates',
                'autodoc_default.html'
            )
            with open(filename) as file:
                content = file.read()
                with current_app.app_context():
                    return render_template_string(
                        content,
                        autodoc=self.generate(groups=groups),
                        **context) 
Example #13
Source File: tasks.py    From getting-started-python with Apache License 2.0 4 votes vote down vote up
def get_books_queue():
    project = current_app.config['PROJECT_ID']

    # Create a queue specifically for processing books and pass in the
    # Flask application context. This ensures that tasks will have access
    # to any extensions / configuration specified to the app, such as
    # models.
    return psq.Queue(
        publisher_client, subscriber_client, project,
        'books', extra_context=current_app.app_context) 
Example #14
Source File: execute_task.py    From freight with Apache License 2.0 4 votes vote down vote up
def run(self):
        with self.app_context:
            self._run() 
Example #15
Source File: execute_task.py    From freight with Apache License 2.0 4 votes vote down vote up
def __init__(self, app_context, task_id, process, chunk_size=4096):
        self.app_context = app_context
        self.task_id = task_id
        self.process = process
        self.chunk_size = chunk_size
        self.cur_offset = 0
        self.last_recv = None
        self.active = True
        threading.Thread.__init__(self)
        self.daemon = True
        self.write_lock = threading.Lock() 
Example #16
Source File: celery.py    From flask-restful-example with MIT License 4 votes vote down vote up
def flask_app_context():
    """
    celery使用Flask上下文
    :return:
    """
    with current_app.app_context():
        return str(current_app.config) 
Example #17
Source File: User.py    From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License 4 votes vote down vote up
def _generate_refresh_token(self):
        with app.app_context():
            refresh_token = create_refresh_token(self.id)
            return refresh_token 
Example #18
Source File: User.py    From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License 4 votes vote down vote up
def _generate_access_token(self):
        with app.app_context():
            expires = datetime.timedelta(days=365)
            access_token = create_access_token(self.id, expires_delta=expires)
            # access_token = create_access_token(self.id)
            return access_token