Django管理命令无法返回dict

时间:2016-04-22 18:30:34

标签: python django

我写了一个管理命令:

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument("member_id", nargs="+", type=str)

    def handle(self, *args, **options):
        return other_function(options["member_id"][0])

调用导入的函数:

def other_function(identifier):
    return {"foo": "bar"}

当我从shell调用另一个函数时,它正常工作;但是,当我使用管理命令时,我得到:

  File "/Volumes/www/bin/../apps/manage.py", line 61, in <module>
    execute_from_command_line(sys.argv)
  File "/Volumes/www/src/django/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/Volumes/www/src/django/django/core/management/__init__.py", line 346, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Volumes/www/src/django/django/core/management/base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Volumes/www/lib/python2.7/site-packages/raven/contrib/django/management/__init__.py", line 41, in new_execute
    return original_func(self, *args, **kwargs)
  File "/Volumes/www/src/django/django/core/management/base.py", line 454, in execute
    self.stdout.write(output)
  File "/Volumes/www/src/django/django/core/management/base.py", line 111, in write
    if ending and not msg.endswith(ending):
AttributeError: 'dict' object has no attribute 'endswith'

管理命令只能返回字符串吗?文档似乎没有这么说,但如果我将handle函数更改为return "foo"则可行。但这似乎很愚蠢。

1 个答案:

答案 0 :(得分:4)

是。它必须返回一个字符串,如果它返回任何东西。 &#34;它可能会返回一个Unicode字符串,该字符串将打印到stdout&#34; https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/