Django runserver from Python script

走远了吗. 提交于 2020-01-19 17:04:06

问题


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?


回答1:


Python has already builtin HTTP server

python -m SimpleHTTPServer

OR you have an alternative to run the django server

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')


来源:https://stackoverflow.com/questions/30893418/django-runserver-from-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!