Handling 3 operands in an expression without raising an exception

Denis McMahon denismfmcmahon at gmail.com
Fri Sep 27 11:16:21 EDT 2013


On Fri, 27 Sep 2013 12:19:53 +0300, Νίκος wrote:

> This is my code as i have it at the moment:
> 
> ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
> os.environ.get('REMOTE_ADDR', "Cannot Resolve") ) try:
> 	gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
> 	city = gi.time_zone_by_addr( ipval )
> 	host = socket.gethostbyaddr( ipval ) [0]
> except socket.gaierror as e:
> 	city = "Άγνωστη Πόλη"
> 	host = "Άγνωστη Προέλευση"

Here is the basic problem: You're trying to do too many things at once in 
a language you don't understand and without any understanding of the 
fundamental underlying concepts of the systems that you're interfacing 
with.

Break the task down into simpler steps and do the steps one at a time:

Calculate ipval

Calculate gi

If ipval is valid, calculate city, else give city a default value

If ipval is valid, calculate host, else give host a default value

Then consider which of the above needs to be contained within a try / 
catch.

Finally, code them as 4 separate units of code, eg:

# instantiate geolocation by ip
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')

# calculate ipval
try:
    ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
              os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
except ( KeyError, TypeError ):
    ipval = some_default

# try and obtain time zone from ip
try:
    city = gi.time_zone_by_addr( ipval )
except (error type[s]):
    city = "Unknown City"

# try and obtain hostname from ip
try:
    host = socket.gethostbyaddr( ipval ) [0]
except ( socket.gaierror ):
    host = "Unknown Host"

Note that there is nothing special about writing it in as few lines as 
code as possible. Writing it out in a way that is easy to understand and 
follow helps make sure it actually works, and makes it a lot easier to 
maintain in future.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list