Search code examples
pythonmysqldjangoapscheduler

django + apscheduler - How to configure APScheduler to use django db connection data in settings.py?


I have a working Django project with its database and model tables.Now, I want to integrate APScheduler and save APScheduler job in the same database as other tables, using the Django database connection.

I have read the User Guide which gives examples of hardcoding db connection string into code:

from pytz import utc

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor


jobstores = {
    'mongo': MongoDBJobStore(),
    'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 3
}
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)

But the config data I already have it in Django setting file.

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'xxxxx',
       'USER': "manager",
       'PASSWORD': "xxxxxxxx",
       'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
       'PORT': '3306',
   }
}

Can I just use Django connection? I don't want to write these data into another properties file to maintain two files.

I ask this basically because I don't want to hard code credentials.

EDIT:

I realized that I can use something like:

'url':          'mysql+mysqldb://' +  settings.DATABASES['default']['USER'] + ':' + 
    settings.DATABASES['default']['PASSWORD'] + '@' +
    settings.DATABASES['default']['HOST'] + '/' +
    settings.DATABASES['default']['NAME']

Now, if my password is encrypted, will APScheduler recognize it?


Solution

  • You likely have already resolved this but there is a 3rd party helper for integrating APScheduler with Django called "django_apscheduler" as mentioned in the docs.

    It can be installed from PyPi using PIP and you can find the docs on GitHub, although they are a little vague.