How to use Django to get the name for the host server?

后端 未结 7 2010
天命终不由人
天命终不由人 2020-12-13 17:18

How to use Django to get the name for the host server?

I need the name of the hosting server instead of the client name?

相关标签:
7条回答
  • 2020-12-13 17:26

    I generally put something like this in settings.py:

    import socket
    
    try:
        HOSTNAME = socket.gethostname()
    except:
        HOSTNAME = 'localhost'
    
    0 讨论(0)
  • 2020-12-13 17:28

    Basically, You can take with request.get_host() in your view/viewset. It returns <ip:port>

    0 讨论(0)
  • 2020-12-13 17:33

    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).

    Alternatively, you can do (original answer below):

    if request.is_secure():
        protocol = 'https'
    else:
        protocol = 'http'
    

    Because is_secure() returns True if request was made with HTTPS.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 17:39

    Try os.environ.get('HOSTNAME')

    0 讨论(0)
  • 2020-12-13 17:47

    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()}/'
    
    0 讨论(0)
提交回复
热议问题