Find Host and Port in a Django Application

2019-08-03 17:35发布

问题:

I'm connecting to the Twitter Streaming API and am setting up the OAuth handshake. I need to request a token and send a callback_url as a params dictionary along with post request.

I've hardcoded in the url for development (http://localhost:8000/oauth) but when I deploy this will change. I want to set up something that will find the host and port and set a reference it. Ideally, looking like "http://%s/oauth" % (domain_name)

I've tried using both the os and socket modules, and code is below:

class OAuth:

    def request_oauthtoken(self):
        name = socket.gethostname()
        ip = socket.gethostbyname(name)
        domain = socket.gethostbyaddr(ip) # Sequence attempts to find the current domain name.  This will add expandability to the calling the API, as opposed to hard coding it in.  It's not returning what I'm expecting


        payload = { 'oauth_callback': 'http://localhost:8000/oauth' }
        print(domain)
        return payload

domain returns ('justins-mbp-2.local.tld', ['145.15.168.192.in-addr.arpa'], ['192.168.15.145'])

name returns the first element of the tuple above and ip returns the last item of the tuple unwrapped from the collection.

I'm looking for a return value of localhost or localhost:8000. I can work with either one.

回答1:

call request.build_absolute_uri(), then extract the domain.

docs:

HttpRequest.build_absolute_uri(location) Returns the absolute URI form of location. If no location is provided, the location will be set to request.get_full_path().

If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request.

Example: "http://example.com/music/bands/the_beatles/?print=true"