Reputation: 11
I am really struggling to work out how to get APScheduler running in my flask application.
App structure:
/app
├── project/
│ ├── __init__.py
│ ├── main.py
├── app.py
app.py:
from project import app
app.run(host='0.0.0.0', port=80, debug=True)
init.py:
from flask import Flask
app = Flask(__name__)
# set up blueprints
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
# set up apscheduler
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler(daemon=True)
scheduler.start()
main.py:
from flask import Blueprint, render_template, Flask
from . import scheduler
import time
main = Blueprint('main', __name__)
@main.route('/schedule_test')
def schedule_test():
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
When I run this I get the error:
ImportError: cannot import name 'scheduler' from 'project' (/app/project/__init__.py)
I'm sure I'm doing something simple wrong, but I can't work it out.
Edit: to be clear, the flask app runs fine when I remove the references to scheduler.
Upvotes: 0
Views: 2666
Reputation: 663
You should move following code from __init__.py
to a separate Python file.
# set up apscheduler
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler(daemon=True)
scheduler.start()
And then from that file, import scheduler
and use it in your flask route.
Check this out:
In Python, how to import from the __init__.py in the same directory
Upvotes: 1