I had a similar use case and handled it by using a custom management command. In my opinion, it's much more elegant than a standalone python script since everything is setup automatically and I can always manually run the command through manage.py
.
You can do this by putting your logic in a module at
your_app/management/commands/your_daily_magic_command.py
Don't forget to also create (if it doesn't already exist):
your_app/management/__init__.py
your_app/management/commands/__init__.py
Inside your_daily_magic_command.py
, it should look something like this:
from django.core.management.base import BaseCommand, CommandError
##import logging
##logger = logging.getLogger(__name__)
class Command(BaseCommand):
#args = '<required_arg1> [optional_arg2]'
help = 'Put your help text here to be shown in manage.py help'
def handle(self, *args, **options):
#if len(args) == 0:
# raise CommandError('Not enough arguments. Please see help')
#if len(args) > 2:
# raise CommandError('Too many arguments. Please see help')
self.stdout.write('Starting my daily magic stuff...')
#self.stdout.write('Arguments: %s' % args)
# Your daily magic logic here
self.stdout.write('Finished my daily magic stuff :)')
##logger.debug("A debug message...")
##logger.info("...using django's logging mechanism")
A nice thing is it'll also handle command line arguments for you. In my example, the single commented lines show you how to use one required and one optional arguments so you can just edit it from there.
There's no need to use the logging
package as you can simply use self.stdout.write
(see code)
For official examples, see django.core.mangement.commands.*
To run your command:
python /path/to/your/project/manage.py your_daily_magic_command
If you really want to use the python logging
package with django's shortcuts, you will need to set up your settings.LOGGING
. Here's an example:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
# You can change your format here
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'console_out': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard',
# 'strm' in Python 2.6. See http://codeinthehole.com/writing/console-logging-to-stdout-in-django/
'stream': sys.stdout,
},
'console_err': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard',
}
},
'loggers': {
'your_app_path.management.commands.your_daily_magic_command': {
'handlers': ['console_out'],
'level': 'DEBUG', # DEBUG level is lower than INFO
'propagate': True,
},
# Default logger: http://stackoverflow.com/questions/5438642/django-setup-default-logging
'': {
# For special handling, see http://code.activestate.com/recipes/576819-logging-to-console-without-surprises/
'handlers': ['console_err'],
'level': 'INFO', # Show only INFO and up
'propagate': True,
},
}
}
In the your_daily_magic_command.py
example above, the double commented (##
) lines show you how to use this.
The logger name can be anything corresponding to your settings.LOGGING['loggers']
entry, but using __name__
to refer to the current module is standard practice.