在Djang中获取当前服务器ip或域

2024-09-30 03:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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,例如:

^{pr2}$

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


编辑

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


Tags: 项目django方法ip服务器imgisrequest
2条回答

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开始

{您可以从^ a1请求获得主机名:

request.get_host()

客户端的远程IP如下(docs):

^{pr2}$

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

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

相关问题 更多 >

    热门问题