我正在尝试使用Django的独立脚本,继承自https://github.com/syntarsus/minimal-django
当我离开调用开发服务器到命令行调用时,事情进展顺利:
python minimal.py runserver
服务器很高兴启动并运行:
Performing system checks...
System check identified no issues (0 silenced).
September 24, 2017 - 00:58:36
Django version 1.11.5, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
我想修改脚本以在Django抽象中降低级别并使用以下命令调用服务器:
from django.core import management
management.call_command('runserver')
这会引发异常
AppRegistryNotReady: Apps aren't loaded yet.
正如在其他SO问题中所建议的那样,我尝试用以下方法覆盖例外:
import django
django.setup()
......但显然它不再起作用,所以我迷路了。
答案 0 :(得分:2)
这对我有用,只需执行python minimal.py
即可调用它,它将运行本地服务器:
<强> minimal.py 强>
import sys
import django
from django.conf import settings
from django.conf.urls import url
from django.core.management import call_command
from django.http import HttpResponse
settings.configure(
DEBUG=True,
SECRET_KEY='A-random-secret-key!',
ROOT_URLCONF=sys.modules[__name__],
)
django.setup()
def index(request):
return HttpResponse('<h1>A minimal Django response!</h1>')
urlpatterns = [
url(r'^$', index),
]
if __name__ == '__main__':
call_command('runserver')