9

The normal way to start the Django server is to run the following command from a terminal or a bash script:

python manage.py runserver [Ip.addr]:[port] 

e.g.

python manage.py runserver 0.0.0.0:8000

How can I start a Django server from a Python script?

One option is the following

import os
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
    from django.core.management import execute_from_command_line
    args = ['name', 'runserver', '0.0.0.0:8000']
    execute_from_command_line(args)

Is there a better way?

4

1 回答 1

16

Python 已经内置了 HTTP 服务器

python -m SimpleHTTPServer

或者你有一个替代方案来运行 django 服务器

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")

from django.core.management import call_command
from django.core.wsgi import get_wsgi_application 
application = get_wsgi_application()
call_command('runserver',  '127.0.0.1:8000')
于 2015-06-17T14:09:41.407 回答