Python 如何使用 Django 获取主机服务器的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4093999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Django to get the name for the host server?
提问by user469652
How to use Django to get the name for the host server?
如何使用 Django 获取主机服务器的名称?
I need the name of the hosting server instead of the client name?
我需要托管服务器的名称而不是客户端名称?
采纳答案by Craig Trader
I generally put something like this in settings.py:
我通常把这样的东西放在settings.py:
import socket
try:
HOSTNAME = socket.gethostname()
except:
HOSTNAME = 'localhost'
回答by Ankit Jaiswal
Try os.environ.get('HOSTNAME')
尝试 os.environ.get('HOSTNAME')
回答by Tobu
If you have a request (e.g., this is inside a view), you can look at request.get_host()which gets you a complete locname (host and port), taking into account reverse proxy headers if any. If you don't have a request, you should configure the hostname somewhere in your settings. Just looking at the system hostname can be ambiguous in a lot of cases, virtual hosts being the most common.
如果您有一个请求(例如,这是在视图中),您可以查看request.get_host()哪个可以获得完整的 locname(主机和端口),并考虑反向代理标头(如果有)。如果您没有请求,则应在设置中的某处配置主机名。在很多情况下,仅查看系统主机名可能会产生歧义,虚拟主机是最常见的。
回答by azalea
Just add to @Tobu's answer. If you have a request object, and you would like to know the protocol (i.e. http / https), you can use request.scheme(as suggested by @RyneEverett's comment).
只需添加到@Tobu's answer。如果您有一个请求对象,并且您想知道协议(即 http/https),您可以使用request.scheme(如@RyneEverett 的评论所建议的那样)。
Alternatively, you can do (original answer below):
或者,您可以这样做(以下原始答案):
if request.is_secure():
protocol = 'https'
else:
protocol = 'http'
Because is_secure()returns Trueif request was made with HTTPS.
因为如果使用 HTTPS 发出请求,则is_secure() 会返回True。
回答by direwolf
Basically, You can take with request.get_host()in your view/viewset. It returns <ip:port>
基本上,您可以request.get_host()在视图/视图集中使用。它返回<ip:port>
回答by Tobias Ernst
If you have a request object, you can use this function:
如果你有一个请求对象,你可以使用这个函数:
def get_current_host(self, request: Request) -> str:
scheme = request.is_secure() and "https" or "http"
return f'{scheme}://{request.get_host()}/'

