【问题标题】:running python module from django shell (manage.py)从 django shell (manage.py) 运行 python 模块
【发布时间】:2012-05-20 14:53:55
【问题描述】:

我正在尝试将数据填充到我的数据库中,并且我想使用 django API 来执行此操作。我编写了一个 python 模块,可以很容易地做到这一点。

但是,在 django shell (manage.py) 中,似乎无法运行我的“populate.py”文件。

是否可以从 django shell 运行我的 populate.py?或者,我应该改为运行常规 python 终端并导入必要的 django 组件吗?无论哪种方式,我都将不胜感激。

【问题讨论】:

  • 您是否尝试从 django shell 中导入填充?导入填充; populate.main() 或类似的东西......

标签: python database django api


【解决方案1】:

您也可以考虑使用loaddata command 或create your own command

【讨论】:

    【解决方案2】:

    这是我从命令行运行 django 的标准包装器。如果您有要运行的 cron 脚本,这也很有用。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os, sys
    # If this script lives in a child directory of the main project directory
    # uncomment the following 2 lines:
    #dir_parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    #sys.path.insert(0, dir_parent)
    
    from django.core.management import setup_environ
    import settings
    setup_environ(settings)
    
    from django.db import transaction
    
    # import whatever you like from app.models or whatever
    # do random stuff.
    
    # If you are *changing* database records,
    # wrap your database code either in:
    @transaction.commit_manually
    def foo():
       ... stuff
       transaction.commit()
    
    # OR end you script with:
    transaction.commit_unless_managed()
    

    评论更新:

    上面提到的变量不是file,而是__file__(即两个下划线file和另外两个下划线)。这总是由 Python 解释器设置为它出现的文件的完整路径。正如评论所说,如果这个脚本位于主目录的子目录中,则文件名的目录为您提供主项目目录的目录名称,并将其添加到sys.path 将确保您的所有导入都正常工作。如果脚本位于 主目录中并且您从那里执行它,那么您不需要这样做。

    【讨论】:

    • 谢谢!但是,我现在得到“回溯(最近一次调用最后一次):文件“”,第 1 行,在 dir = os.path.dirname(os.path.dirname(os.path. realpath(file))) NameError: name 'file' is not defined"
    • 谢谢!我只是在那里遇到了一些语法问题。现在工作。但是,我仍然决定将其包装为自定义 django-admin 命令,以避免将来需要这种东西。
    【解决方案3】:

    试试 django-extensions,它有一个 runscript 命令放在脚本目录中。

    奇怪的是,主文档中似乎缺少该命令,但如果您 google django-extensions runscript,您会找到示例和文档。

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 2014-09-19
      • 2011-06-18
      • 2012-08-28
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      相关资源
      最近更新 更多