Στις 27/9/2013 6:16 μμ, ο/η Denis McMahon έγραψε:
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.
Sure your method follows the the logic in a straighforward way
step-by-step but i just dont want to spent almost 20 lines of code just
to calculate 2 variables(city and host).
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "Άγνωστη Πόλη"
host = "Άγνωστη Προέλευση"
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:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )
The above code works in less lines of codes and because the assignment
of the vars happen before the try:/except: block, if something fails
during try: we can tell by looking at the values of city or host.
Also its being logged at the err.out too.
Only problem is that iam handlign address related issues and not the
case of when gi fails.
But i dont know how to do that.
except (error type[s]): i saw in your code but iam not sure what exactly
this is supposed to handle.
--
https://mail.python.org/mailman/listinfo/python-list