我想在一个多余的config.ini中指定manage.py runserver侦听的默认端口。有没有比解析sys. exe更简单的解决方案?在manage.py和插入配置端口Argv ?
目标是运行./manage.py runserver,而不必每次都指定地址和端口,而是让它从config.ini中获取参数。
我想在一个多余的config.ini中指定manage.py runserver侦听的默认端口。有没有比解析sys. exe更简单的解决方案?在manage.py和插入配置端口Argv ?
目标是运行./manage.py runserver,而不必每次都指定地址和端口,而是让它从config.ini中获取参数。
当前回答
从Django 1.9开始,我找到的最简单的解决方案(基于Quentin stford - fraser的解决方案)是在manage.py中添加几行代码,在调用runserver命令之前动态修改默认端口号:
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")
import django
django.setup()
# Override default port for `runserver` command
from django.core.management.commands.runserver import Command as runserver
runserver.default_port = "8080"
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
其他回答
在.bashrc中创建环境变量 出口RUNSERVER_PORT = 8010 创建别名 alias runserver='django-admin runserver $RUNSERVER_PORT'
我使用zsh和virtualenvs包装。我把出口项目后激活脚本和分配端口为每个项目。
workon someproject
runserver
在上一个版本的Django(目前:4.0.3)中,你可以在settings.py文件中添加这些行
from django.core.management.commands.runserver import Command as runserver
runserver.default_port = "8000"
在你的项目manage.py文件中添加
from django.core.management.commands.runserver import Command as runserver
然后在def main()中:
runserver.default_port = "8001"
我们创建了一个新的“runserver”管理命令,它是标准命令的精简包装,但改变了默认端口。粗略地说,你创建management/commands/runserver.py并放入如下内容:
# Override the value of the constant coded into django...
import django.core.management.commands.runserver as runserver
runserver.DEFAULT_PORT="8001"
# ...print out a warning...
# (This gets output twice because runserver fires up two threads (one for autoreload).
# We're living with it for now :-)
import os
dir_path = os.path.splitext(os.path.relpath(__file__))[0]
python_path = dir_path.replace(os.sep, ".")
print "Using %s with default port %s" % (python_path, runserver.DEFAULT_PORT)
# ...and then just import its standard Command class.
# Then manage.py runserver behaves normally in all other regards.
from django.core.management.commands.runserver import Command
I was struggling with the same problem and found one solution. I guess it can help you. when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000 as default port number which can be configured in your python environment. In your python setting, go to <your python env>\Lib\site-packages\django\core\management\commands\runserver.py and set 1. default_port = '<your_port>' 2. find this under def handle and set if not options.get('addrport'): self.addr = '0.0.0.0' self.port = self.default_port
现在如果你运行"python manage.py runserver",它将默认运行在"0.0.0.0 "上:
享受编码.....