在外部python脚本中使用Django模型

时间:2022-05-23 01:14:08

I was very confused today.

我今天很困惑。

I was trying to use my django app models in my python script.

我试图在python脚本中使用django应用程序模型。

here is my approach

这是我的方法

import os, sys

sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User

I was confused why its giving me

我很困惑为什么它给了我

ImportError: Could not import settings 'openstack_dashboard.settings' (Is it on sys.path?): cannot import name auth

Upon checking I created a a file called creds that includes

在检查之后,我创建了一个名为creds的文件,其中包括

export PYTHONPATH=$PYTHONPATH:/var/www/cloudloon/horizon/; 
export DJANGO_SETTINGS_MODULE=openstack_dashboard.settings; django-admin.py shell;

and from terminal window where creds file is located, I do

从creds文件所在的终端窗口,我可以。

source creds

and from that django-admin.py shell, I could import any of my django app models without any errors.

从那django-admin。py shell,我可以导入我的django应用程序模型,没有任何错误。

Why it doesn't work in my python script?

为什么它不能在我的python脚本中工作?

I am done with Django, What I need to do is to create a python-daemon script that will access my django app models.

我已经完成了Django的工作,我需要创建一个python-daemon脚本,它将访问我的Django应用程序模型。

I am working with in Ubuntu 12.04 that has django 1.5

我正在Ubuntu 12.04中使用django 1.5

As I looking for solutions, I did this:

当我寻找解决方案时,我这样做了:

import os, sys

sys.path.append("/var/www/cloudloon/horizon")
sys.path.append("/var/www/cloudloon/horizon/openstack_dashboard")
# os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                          "openstack_dashboard.settings")

print os.environ["DJANGO_SETTINGS_MODULE"]
for s in sys.path:
    print s

from django.contrib.auth.models import User

heres the output: http://paste.openstack.org/show/48787/

这是输出:http://paste.openstack.org/show/48787/

as you can see, the directory where settings.py is located are present on my sys.path, however, It was still unable to import openstack_dashboard.settings.

如您所见,目录中的设置。py在我的系统上。然而,它仍然无法导入openstack_dashboard.settings。

Thanks everyone.

谢谢每一个人。

2 个解决方案

#1


23  

You need to write a custom management command, instead of doing these weird acrobatics.

您需要编写一个自定义管理命令,而不是执行这些奇怪的杂技动作。

Create a module called management (in other words, create a directory management and inside it create an empty __init__.py file) inside the directory of any app that you have listed in INSTALLED_APPS. So if you have myapp, you would create:

创建一个名为management的模块(换句话说,创建一个目录管理,并在其中创建一个空的__init__)。py文件)在INSTALLED_APPS中列出的任何应用程序的目录中。如果你有myapp,你会创建:

myapp
 |
 > management
 | | __init__.py
 > models.py
 > views.py

Then in the management directory, create another module commands and in it create a file which is the name of your command; for example my_command.py, like this:

然后在管理目录中,创建另一个模块命令,并在其中创建一个文件,该文件是您的命令的名称;例如my_command。py,像这样:

myapp
 |
 > management
 | | __init__.py
 | | commands
 | | | __init__.py
 | | | my_command.py
 > models.py
 > views.py

In my_command.py, write this boilerplate code:

在my_command。py,写这个样板代码:

from django.core.management.base import BaseCommand, CommandError
from myapp.models import MyModel

class Command(BaseCommand):
    help = 'Does some magical work'

    def handle(self, *args, **options):
        """ Do your work here """
        self.stdout.write('There are {} things!'.format(MyModel.objects.count()))

Once you save the file, you'll be able to do python manage.py my_command and it will have access to all your models and settings.

保存文件之后,就可以执行python管理了。my_command,它将访问所有模型和设置。

If you need to run it as a daemon, Daniel Roseman wrote django-initd which does exactly that. Once you have installed it:

如果您需要将它作为一个守护程序运行,Daniel Roseman编写了django-initd,它就是这样做的。一旦安装完毕:

from django.core.management.base import CommandError
from daemon_command import DaemonCommand
from myapp.models import MyModel

class Command(DaemonCommand):
    help = 'Does some magical work'

    def loop_callback(self, *args, **options):
        """ Do your work here """
        self.stdout.write('There are {} things!'.format(MyModel.objects.count()))

Once you have that done from the github readme:

一旦你完成了github的readme:

The important parts of such a process are these:

    * it comes up automatically on server startup
    * it logs errors and information to a named location, which is configurable
    * if the process dies, it restarts itself straight away 

[...]

Run the command as normal, but pass one of --start, --stop or --restart to 
work as a daemon. Otherwise, the command will run as a standard application.

#2


8  

The below script should work provided that the layout of your project (and the path to your settings file) looks like this:

如果项目的布局(以及设置文件的路径)是这样的,下面的脚本应该可以工作:

/var/www/cloudloon/horizon/openstack_dashboard/settings.py

/var/www/cloudloon/horizon/openstack_dashboard / settings.py

#!/usr/bin/env python
import os, sys

sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User

I believe the problem you're seeing is due to the arrangement of your project, or that you need to append another directory level to the sys.path call in the script.

我相信您看到的问题是由于您的项目的安排,或者您需要向sys追加另一个目录级别。脚本中的路径调用。

Edit:

编辑:

Looking at your github project, horizon and openstack_dashboard are on the same directory level. What you'd want to do is set your sys.path to one level higher:

查看github项目,horizon和openstack_dashboard位于同一个目录级别。你要做的是设置系统。通向更高一级的路径:

sys.path.append("/var/www/cloudloon")

#1


23  

You need to write a custom management command, instead of doing these weird acrobatics.

您需要编写一个自定义管理命令,而不是执行这些奇怪的杂技动作。

Create a module called management (in other words, create a directory management and inside it create an empty __init__.py file) inside the directory of any app that you have listed in INSTALLED_APPS. So if you have myapp, you would create:

创建一个名为management的模块(换句话说,创建一个目录管理,并在其中创建一个空的__init__)。py文件)在INSTALLED_APPS中列出的任何应用程序的目录中。如果你有myapp,你会创建:

myapp
 |
 > management
 | | __init__.py
 > models.py
 > views.py

Then in the management directory, create another module commands and in it create a file which is the name of your command; for example my_command.py, like this:

然后在管理目录中,创建另一个模块命令,并在其中创建一个文件,该文件是您的命令的名称;例如my_command。py,像这样:

myapp
 |
 > management
 | | __init__.py
 | | commands
 | | | __init__.py
 | | | my_command.py
 > models.py
 > views.py

In my_command.py, write this boilerplate code:

在my_command。py,写这个样板代码:

from django.core.management.base import BaseCommand, CommandError
from myapp.models import MyModel

class Command(BaseCommand):
    help = 'Does some magical work'

    def handle(self, *args, **options):
        """ Do your work here """
        self.stdout.write('There are {} things!'.format(MyModel.objects.count()))

Once you save the file, you'll be able to do python manage.py my_command and it will have access to all your models and settings.

保存文件之后,就可以执行python管理了。my_command,它将访问所有模型和设置。

If you need to run it as a daemon, Daniel Roseman wrote django-initd which does exactly that. Once you have installed it:

如果您需要将它作为一个守护程序运行,Daniel Roseman编写了django-initd,它就是这样做的。一旦安装完毕:

from django.core.management.base import CommandError
from daemon_command import DaemonCommand
from myapp.models import MyModel

class Command(DaemonCommand):
    help = 'Does some magical work'

    def loop_callback(self, *args, **options):
        """ Do your work here """
        self.stdout.write('There are {} things!'.format(MyModel.objects.count()))

Once you have that done from the github readme:

一旦你完成了github的readme:

The important parts of such a process are these:

    * it comes up automatically on server startup
    * it logs errors and information to a named location, which is configurable
    * if the process dies, it restarts itself straight away 

[...]

Run the command as normal, but pass one of --start, --stop or --restart to 
work as a daemon. Otherwise, the command will run as a standard application.

#2


8  

The below script should work provided that the layout of your project (and the path to your settings file) looks like this:

如果项目的布局(以及设置文件的路径)是这样的,下面的脚本应该可以工作:

/var/www/cloudloon/horizon/openstack_dashboard/settings.py

/var/www/cloudloon/horizon/openstack_dashboard / settings.py

#!/usr/bin/env python
import os, sys

sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User

I believe the problem you're seeing is due to the arrangement of your project, or that you need to append another directory level to the sys.path call in the script.

我相信您看到的问题是由于您的项目的安排,或者您需要向sys追加另一个目录级别。脚本中的路径调用。

Edit:

编辑:

Looking at your github project, horizon and openstack_dashboard are on the same directory level. What you'd want to do is set your sys.path to one level higher:

查看github项目,horizon和openstack_dashboard位于同一个目录级别。你要做的是设置系统。通向更高一级的路径:

sys.path.append("/var/www/cloudloon")