Handling 3 operands in an expression without raising an exception

Dave Angel davea at davea.name
Thu Sep 26 10:22:29 EDT 2013


On 26/9/2013 09:34, Νίκος wrote:

> Στις 26/9/2013 3:53 μμ, ο/η Antoon Pardon έγραψε:
>> Op 26-09-13 14:39, Νίκος schreef:
>>> Yes, you are right, in my shell it fails too givign the same error
>>> message as yours, while on the other had in the websste is working.
>>>
>>> Can you explain this please?
>>> why doesnt it fail to both enviroments?
>>
>> Your site and your shell are two different environments. The state
>> of the website environment lets your code succeed while the state
>> of the shell environment, doesn't.
>>
> What modification does it need to also work in the shell environmentthe 
> [0] at the end is what complicates things.

Not at all.  What complicates/confuses things is trying to do too much
in one line.

The line is trying to solve two separate things.  You might now
understand the first of them; the fetching of multiple environment
variables that may or may not exist.

The second thing is the function call to gethostbyname().  If fed
invalid data, this call will throw an exception.  So you need to either
put it in a try/catch or somehow pretend that you can know what
constitutes invalid data.  One example of invalid data is your default
string.  Another might be if one of those environment variables exists,
but isn't reasonable.  And a third might be if the domain server
temporarily refuses to recognize a valid hostname.

I'd say you need to put the gethostbyname() in a try/catch, and then
supply some reasonable bogus string for host.  Only you will know what
to use there;  depending on what you're going to use it for.


ipval = (os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Please throw a gaierror exception")
try:
     host = socket.gethostbyaddr(ipval) [0]
except socket.gaierror as exc;
     host = "Unknown host"

I don't know the gethostbyaddr(), so i don't know if there are other
exceptions you should also try to catch.

-- 
DaveA





More information about the Python-list mailing list