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

How to use logger in flask app for outside app contexts (flask-apscheduler) #176

Open
Shivappa opened this issue Jul 15, 2021 · 4 comments

Comments

@Shivappa
Copy link

Facing a context issue for the scheduled jobs.
Issue is explained here.
https://stackoverflow.com/questions/68320718/how-to-use-logger-in-flask-app-for-outside-app-contexts-flask-apscheduler

@viniciuschiele
Copy link
Owner

You need to create a new Flask context within your task like this: https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/flask_context.py#L22

You can also the the Flask app from the APScheduler object:

with apscheduler.app.app_context();
    pass

@mxdev88
Copy link
Contributor

mxdev88 commented Aug 10, 2021

I ran into the same issue and fixed it by adding what you suggest in the func. However I was just wondering whether this could be improved within the library to make it automatic? I was thinking decorating func within APScheduler.add_job should work?

e.g. l.166 https://github.com/viniciuschiele/flask-apscheduler/blob/master/flask_apscheduler/scheduler.py, when self.app is known at time of adding a job, could something like below be done?

...
        fix_job_def(job_def)
        job = self._scheduler.add_job(**job_def)
        if self.app:
            job.func = with_app_context(job.func)
        return job
...

This should ensure the func is always run with an app context. Any thoughts on this?

@viniciuschiele
Copy link
Owner

This doesn't work because jobs can be stored in database and when you shutdown your app and start it again, the jobs would not come attached to with_app_context.
I couldn't find a nice solution for this problem yet.

@mxdev88
Copy link
Contributor

mxdev88 commented Aug 14, 2021

@viniciuschiele I see your point. How about decorating BaseExecutor.submit_job instead then? After initializing the scheduler, could loop through the scheduler executors to make sure they will submit job with the app context.
Do you think that would work then?

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

3 participants