Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Job running without Flask app context #50

Closed
timorthi opened this issue Feb 28, 2018 · 4 comments
Closed

Job running without Flask app context #50

timorthi opened this issue Feb 28, 2018 · 4 comments

Comments

@timorthi
Copy link

timorthi commented Feb 28, 2018

Hi, I'm trying to save to my db in one of my jobs, but I am getting the out of context error: RuntimeError: No application found. Either work inside a view function or push an application context.

Here's a simple example that tests for the app context.

$ export FLASK_APP=app.py
$ flask run
# app.py

from flask import Flask, has_app_context
from flask_rq2 import RQ

app = Flask(__name__)
app.config['RQ_REDIS_URL'] = 'redis://127.0.0.1:6379/0'

rq = RQ(app)


@rq.job
def add(x, y):
    print(has_app_context()) # False
    return x + y


@app.route('/')
def index():
    add.queue(1, 3)
    return 'hello world!'

I can get around this by using ScriptInfo().load_app(), or with a delayed app instance import, but that's not ideal.

from flask.cli import ScriptInfo

@rq.job
def add(x, y):
    with ScriptInfo().load_app().app_context():
        print(has_app_context()) # True
    return x + y
@rq.job
def add(x, y):
    from module_where_app_is_created import app
    with app.app_context():
        print(has_app_context()) # True
    return x + y
@timorthi timorthi changed the title Job running outside of app context Job running without Flask app context Feb 28, 2018
@jezdez
Copy link
Member

jezdez commented Mar 2, 2018

I tried your code and wasn't able to reproduce it. Are you using the latest version of flask-rq2? I changed a lot of how this works in d4d5e52.

@jezdez
Copy link
Member

jezdez commented Mar 2, 2018

See https://github.com/jezdez/rq2test for a quick test as well.

@timorthi
Copy link
Author

timorthi commented Mar 2, 2018

Silly me... After looking at your test example I saw where I went wrong - I was starting my worker process using rq worker instead of flask rq worker. Using the latter solved the problem for me.

My bad for overlooking the CLI support section in the docs, but do you think adding an example of this to the Getting Started section would prevent similar confusion down the line?

@jezdez
Copy link
Member

jezdez commented Mar 2, 2018

@timorthi AH, gotcha, that'd explain it. Thanks for checking :) I opened #52 to follow-up on this, a getting started guide is a great idea.

@jezdez jezdez closed this as completed Mar 2, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants