我有一个类似的用例并使用custom management command 处理它。在我看来,它比独立的 python 脚本要优雅得多,因为一切都是自动设置的,我总是可以通过 manage.py 手动运行命令。
你可以通过将你的逻辑放在一个模块中来做到这一点
your_app/management/commands/your_daily_magic_command.py
不要忘记也创建(如果它不存在):
your_app/management/__init__.py
your_app/management/commands/__init__.py
在your_daily_magic_command.py 内部,它应该看起来像这样:
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")
一件好事是它还可以为您处理命令行参数。在我的示例中,单个注释行向您展示了如何使用一个必需参数和一个可选参数,以便您可以从那里进行编辑。
无需使用logging 包,您只需使用self.stdout.write(见代码)
官方例子见django.core.mangement.commands.*
运行你的命令:
python /path/to/your/project/manage.py your_daily_magic_command
如果你真的想使用带有 django 快捷方式的 python logging 包,你需要设置你的 settings.LOGGING。这是一个例子:
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,
},
}
}
在上面的 your_daily_magic_command.py 示例中,双注释 (##) 行向您展示了如何使用它。
记录器名称可以是与您的settings.LOGGING['loggers'] 条目对应的任何名称,但使用__name__ 来引用当前模块是标准做法。