简体   繁体   English

运行Django命令的Python脚本

[英]Python script to run Django commands

I want to run a python scripts which should do: 我想运行一个应该执行的python脚本:

  1. Create a django project: django-admin startproject foobar 创建一个django项目: django-admin startproject foobar
  2. Create a app in the project: python manage.py barfoo 在项目中创建一个应用程序: python manage.py barfoo
  3. Add an entry of newly created app barfoo in the setting's INSTALLED_APP . 在设置的INSTALLED_APP添加新创建的应用程序barfoo的条目。

How can I achieve this? 我该如何实现?

There seems to be a pythonic way to do #1 and #2 似乎有一种Pythonic的方式来执行#1和#2

https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

from django.core import management
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)

Read a little abour subprocess and Popen method. 阅读一点abour子过程和Popen方法。 This might be what you're looking for. 这可能是您要寻找的。

  1. Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()

  2. Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()

3. I know that's not a perfect code, but I'm just giving an idea. 3.我知道这不是一个完美的代码,但我只是给出一个想法。

with open("settings.py", 'r') as file:
    settings = file.readlines()

new_settings = []
for line in settings:
    if "INSTALLED APPS" in line:
        new_settings.append(line.replace("INSTALLED_APPS = (", "INSTALLED_APPS = (\n'%s'," % your_app_name))
    else:
        new_settings.append(line)
with open("settings.py", 'w') as file:
    file.write("".join(new_settings))

6 years later I stumbled upon this question trying to figure out how to write some tests for an app which only add a custom template tag that interact with other apps in the project. 6年后,我偶然发现了这个问题,试图弄清楚如何为应用编写一些测试,这些测试仅添加与项目中其他应用交互的自定义​​模板标签。 Hope this can help someone. 希望这可以帮助某人。

Building on @groovehunter answer: the official documentation now (Django 1.10) inculdes this feature outside dev. 建立在@groovehunter答案上:现在的正式文档 (Django 1.10)包含了dev外的此功能。

Note that you need to change current directory to the created project before call startapp . 请注意,您需要在调用startapp之前将当前目录更改为创建的项目。 See this answer for more details 查看此答案以获取更多详细信息

from django.core import management
import os

management.call_command('startproject', 'foobar')
os.chdir('foobar')
management.call_command('startapp', 'barfoo')

or you can use the additional argumento to startproject to create the project in the current directory, if you're sure there won't be problems: 或者,如果您确定不会出现问题,也可以使用其他参数来startproject project以在当前目录中创建项目:

from django.core import management

management.call_command('startproject', 'foobar', '.')
management.call_command('startapp', 'barfoo')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM