脱离django调试py文件的方法
需要调试某个单独的py模块的时候,启动整个django工程看不到程序抛出的信息,也不能单步调试,很麻烦,通过google在stackoverflow上搜到解决办法:
第一种方法:导入settings对象(注意是对象不是模块)
from django.conf import settings
settings.configure(
DATABASE_ENGINE='postgresql_psycopg2',
DATABASE_NAME='FOO',
DATABASE_USER='username',
DATABASE_PASSWORD='password',
DATABASE_HOST='localhost',
DATABASE_PORT='5432',
INSTALLED_APPS=('foo',)
)
如果直接settings.configure(),会报错找不到数据库的配置,所以只能按上面的办法显式指明。
更好的办法是:
import django.core.management
from foo import settings
django.core.management.setup_environ(settings)
这里的关键就是django.core.management的setup_environ函数,该函数源文件docstring的说明:
Configures the runtime environment. This can also be used by external
scripts wanting to set up a similar environment to manage.py.
Returns the project directory (assuming the passed settings module is
directly in the project directory).
The "original_settings_path" parameter is optional, but recommended, since
trying to work out the original path from the module can be problematic.
目的就是调试外部py文件的时候提供一个django同样的环境