2

I have a flask-script command that spawns a long sequence of greenlets. The problem is, these greenlets are unable to access my app context. I get a "> failed with RuntimeError" at all times (accessing app.logger, per example). Suggestions?

On of my attempts: spawn(method, app, arg1, arg2)

def spawn(app, arg1, arg2):
    with app.app_context():
        app.logger.debug('bla bla') # doesn't work
        ... do stuff
Italo Maia
  • 1,956
  • 3
  • 18
  • 31

2 Answers2

2

Edit: below gives you access to the request object, but not the current_app, probably not what you are searching for.

You are probably looking for flask.copy_current_request_context(f) which is documented here: http://flask.pocoo.org/docs/0.10/api/#flask.copy_current_request_context

Example:

import gevent
from flask import copy_current_request_context

@app.route('/')
def index():
    @copy_current_request_context
    def do_some_work():
        # do some work here, it can access flask.request like you
        # would otherwise in the view function.
        ...
    gevent.spawn(do_some_work)
    return 'Regular response'
emeier
  • 111
  • 2
  • Thanks Emeier. Actually, I had to overwrite the __call__ method from my flask-script command in order to make things work. I probably made a big fuss for too little xP~ – Italo Maia Mar 13 '15 at 03:12
0

you can pass a copy of the relevant info from the request, e.g.

import gevent

@app.route('/')
def index():
    def do_some_work(data):
        # do some work here with data
        ...
    data = request.get_json()
    gevent.spawn(do_some_work, data)
    return 'Regular response'
vim
  • 845
  • 16
  • 13
  • If anything in `do_some_work` requires application context, this will not work. That includes any database access if you are using flask-sqlalchemy, flask-pymongo, etc. – Efrem Rensi Dec 03 '19 at 18:32