我刚刚成功地在Flask中使用request.host
和request.url_root
获取我的应用程序服务器主机名,但是这两个字段都返回带有其端口的请求主机名。
我想要使用一个仅返回请求主机名而不必进行字符串替换的字段/方法,如果有的话。
在Juan E的回答基础上,这是我对Python3的解决方案:
Solution for Python3:
from urllib.parse import urlparse
o = urlparse(request.base_url)
host = o.hostname
FlaskдҢүз”Ёзљ„WSGIе·Өе…·еЊ…WerkzeugжІҰжњ‰иү”е›һдё»жњғеђҚзљ„ж–№жі•пәЊдҢ†ж‚ЁеЏҮд»ӨдҢүз”ЁPythonзљ„urlparseжЁҰеқ—д»ҺWerkzeugзљ„з»“жһњдёиҺ·еЏ–дё»жњғеђҚпәљ
python 3
from urllib.parse import urlparse
o = urlparse(request.base_url)
print(o.hostname)
Python 2
from urlparse import urlparse
o = urlparse("http://127.0.0.1:5000/")
print(o.hostname) # will display '127.0.0.1'
这在我的Python-Flask应用程序中可以正常工作。
from flask import Flask, request
print "Base url without port",request.remote_addr
print "Base url with port",request.host_url
如果你想在 Flask 模板 (jinja2) 中使用它:
<!--Without port -->
{{ request.remote_addr }}
<!-- With port -->
{{ request.hostname }}
>>> from werkzeug.urls import url_parse
>>> url_parse('https://auth.dev.xevo-dev.com:443/path/to/me?query1=x&query2')
URL(scheme='https', netloc='auth.dev.xevo-dev.com:443', path='/path/to/me', query='query1=x&query2', fragment='')
>>> url_parse('https://auth.dev.xevo-dev.com:443/path/to/me?query1=x&query2').host
'auth.dev.xevo-dev.com'
>>>