如何在Django应用程序的views.py中执行外部脚本?

时间:2019-04-23 11:57:59

标签: python django python-2.7

以下是我的django文件结构

  • myproject
  • myapp

    • 移民
    • 静态
    • 模板

      • myapp
        • demo.html
    • urls.py

    • views.py
    • models.py
    • admin.py
    • apps.py
    • tests.py
  • 脚本
    • demo_script.py
  • manage.py

我想知道如何从views.py执行脚本Scripts / demo_script.py(在应用程序“ myapp”之外),如果执行成功,请在myapp / templates / myapp上显示“成功” /demo.html,否则在同一html页面上显示“执行失败”。

谢谢!

1 个答案:

答案 0 :(得分:0)

只需使用:

relative_path = "scripts/demo_script.py"
# or
absolute_path = os.path.join(settings.BASE_DIR, "scripts", "demo_script.py")

exec(open(relative_path or absolute_path).read())  # execute the py file

Django中引用的所有路径都相对于BASE_DIRBASE_DIR是您manage.py所在的地方。