如何正确设置ALLOWED_HOST以允许网络中的其他机器访问服务器

问题描述 投票:0回答:2

机器 TestPC-A 中的 Django 服务器,地址为 192.25.56.120

我希望可以从同一网络 192.25.56.xxx 中的计算机访问它。

我配置了什么

1。设置.py


ALLOWED_HOSTS = ["127.0.0.1", "localhost", "TestPC-A" , "0.0.0.0", "192.25.56.120"]

#and this which I am not sure if this is necessary:

CSRF_TRUSTED_ORIGINS = [
    "http://127.0.0.1",
    "https://127.0.0.1",
    "http://localhost",
    "https://localhost",
    "https://TestPC-A",
    "http://TestPC-A",
]

2。运行服务器.bat

@echo off
REM Activate virtual environment in the current terminal session and run server
cmd /k ".venv\Scripts\activate && python manage.py runserver_plus --cert-file cert.pem --key-file key.pem 0.0.0.0:8000"

我尝试在 Windows 主机文件 C:\Windows\System32\drivers tc\hosts 中添加以下内容

192.25.56.120    TestPC-A

我重新启动服务器,但在另一台计算机的网络浏览器上未加载网页

https://TestPC-A:8000/

我还需要设置什么?

python django
2个回答
3
投票

为了子孙后代。 使网络上的其他计算机可以查看您的开发服务器。

假设您有两台机器

machine A
machine B
。将两台机器连接到一个公共网络(甚至可能是您手机的 wifi)。

如果

machine A
将是您的服务器,即
machine A
是您的源代码一直所在的机器,而
machine A
是您运行命令的位置:

python manage.py runserver

检查在此网络上分配的 IP 地址

machine A
[stackoverflow]将此IP地址添加到Django设置中
ALLOWED_HOSTS
[django-docs]
list
这样Django将允许机器托管它。

例如,如果 IP 地址是

172.200.42.1
,请将其添加到
ALLOWED_HOSTS
,然后运行命令:

python manage.py runserver 0.0.0.0:7000 # <—- runserver on port 7000 on this host on this network

由于

machine B
连接到与
machine A
相同的网络,请使用
machine B
上的任何 http 客户端(甚至您的互联网浏览器可以服务)连接到
machine A
,即您的服务器使用套接字地址
172.200.42.1:7000
[1].


[1] 我们将使用此套接字地址,因为应用程序在网络上的 IP 地址

machine A
上运行,并且应用程序在端口
172.200.42.1
上运行。

    


-1
投票

    7000
  1. 运行服务器
  2. 重要:在防火墙添加
  3. 入站规则
  4. ,允许连接适用于域、私有、公共、TCP ThePort
© www.soinside.com 2019 - 2024. All rights reserved.