在 Django 中获取当前的服务器 IP 或域



我在Python Django项目中有一个util方法:

def getUserInfo(request):
user = request.user
user_dict = model_to_dict(user)
user_dict.pop("password")
user_dict.pop("is_superuser")
user_dict["head_img"] = user.head_img.url # there is `/media/images/users/head_img/blob_NOawLs1`

我想在其前面添加我的服务器域或 ip,例如:

http://www.example.com:8000/media/images/users/head_img/blob_NOawLs1

如何获取当前服务器ip(或域)?


编辑

我不打算获取远程 IP,我只想获取服务器 ip。我的意思是,我将 Django 编写为后端服务器,当它运行时,我如何获取服务器 ip?或域。

您可以从请求中获取主机名,如下所示(docs):

request.get_host()

以及客户端的远程 IP,如下所示(文档):

request.META['REMOTE_ADDR']

获取服务器IP有点棘手,如这个SO答案所示, 它给出了这个解决方案:

import socket
# one or both the following will work depending on your scenario
socket.gethostbyname(socket.gethostname())
socket.gethostbyname(socket.getfqdn())

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.META

还有另一种选择:

import requests server_ip = requests.get("https://httpbin.org/ip").json()['origin']

当 Django 启动时

like:http://127.0.0.1:1024

# formate: {scheme}://{host}
host_addr =  request._current_scheme_host

最新更新