I was looking through some code for a library called django-cas and spotted this line:
protocol = ('http://', 'https://')[request.is_secure()]
What exactly does this line mean/do?
I was looking through some code for a library called django-cas and spotted this line:
protocol = ('http://', 'https://')[request.is_secure()]
What exactly does this line mean/do?
It picks one of two values based on the boolean outcome.
('http://', 'https://') is a tuplerequest.is_secure() produces a boolean result, True or False.int, and True == 1, False == 0.Thus, if the request was secure (used SSL encryption, over https) the protocol will be set to https:// too.
More recent versions of Python (2.5 and up) allow for a conditional expression, which would be more readable:
protocol = 'https://' if request.is_secure() else 'http://'
This just selects 0 or 1 index element from the tuple, as
True equals 1, and False equals 0
>>> secure = True
>>> ('http','https')[0]
'http'
>>> ('http','https')[1]
'https'
>>> ('http','https')[secure]
'https'
>>> ('http','https')[False]
'http'
However, a cleaner way of doing this would be :
protocol = "http" if request.is_secure() else "https"
This is a clever ternary operator in python. Based on the boolean result it will pick one of those two strings.
If False (0) will pick the first one and if True (1) the second one.
Look it like this:
>>>('http://', 'https://')[False]
'http://'
>>>('http://', 'https://')[True]
'https://'
It can also be achieved like this:
protocol = 'https://' if request.is_secure() else 'http://'
request.is_secure() will evaluate to True if the connection is secure (HTTPS: HTTP over TLS) or False if non-secure (standard HTTP).
So, if request.is_secure() is True, then:
protocol = ('http://', 'https://')[request.is_secure()]
# Will resolve as:
protocol = ('http://', 'https://')[True]
# Which is:
protocol = ('http://', 'https://')[1]
# And results in.
protocol == 'https://'
Or, if request.is_secure() is False, then:
protocol = ('http://', 'https://')[request.is_secure()]
# Will resolve as:
protocol = ('http://', 'https://')[False]
# Which is:
protocol = ('http://', 'https://')[0]
# And results in.
protocol == 'http://'
True and False resolve to the integers 1 and 0 respectively because bool is a sub-class of int.The purpose of this is to determine what HTTP scheme (secure or non-secure) to use for links.