我有一个 DataFrame common_ips
,其中包含IP,如下所示。
我需要完成两个基本任务:
这是我在做什么:
import json
import urllib
import re
baseurl = 'http://ipinfo.io/' # no HTTPS supported (at least: not without a plan)
def isIPpublic(ipaddress):
return not isIPprivate(ipaddress)
def isIPprivate(ipaddress):
if ipaddress.startswith("::ffff:"):
ipaddress=ipaddress.replace("::ffff:", "")
# IPv4 Regexp from https://stackoverflow.com/questions/30674845/
if re.search(r"^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*", ipaddress):
# Yes, so match, so a local or RFC1918 IPv4 address
return True
if ipaddress == "::1":
# Yes, IPv6 localhost
return True
return False
def getipInfo(ipaddress):
url = '%s%s/json' % (baseurl, ipaddress)
try:
urlresult = urllib.request.urlopen(url)
jsonresult = urlresult.read() # get the JSON
parsedjson = json.loads(jsonresult) # put parsed JSON into dictionary
return parsedjson
except:
return None
def checkIP(ipaddress):
if (isIPpublic(ipaddress)):
if bool(getipInfo(ipaddress)):
if 'bogon' in getipInfo(ipaddress).keys():
return 'Private IP'
elif bool(getipInfo(ipaddress).get('org')):
return getipInfo(ipaddress)['org']
else:
return 'No organization data'
else:
return 'No data available'
else:
return 'Private IP'
并使用
将其应用于我的common_ips
DataFrame
common_ips['Info'] = common_ips.IP.apply(checkIP)
但是它花费的时间比我预期的要长。对于某些IP ,它是提供了错误的信息。
例如:
在我对它进行交叉检查时应该位于AS19902 Department of Administrative Services
的地方
和
我在这里想念什么?以及如何以更Python化的方式完成这些任务?
答案 0 :(得分:0)
毯子except:
基本上总是一个错误。您将返回None
,而不是处理服务器上的任何异常或错误响应,当然,其余代码将无法恢复。
作为第一步调试,只需执行try
/ except
处理即可。也许那么您就可以找到一种方法,在某些情况下,您可以将其返回一些更详细的错误处理程序,这些情况您知道如何从中恢复。
def getipInfo(ipaddress):
url = '%s%s/json' % (baseurl, ipaddress)
urlresult = urllib.request.urlopen(url)
jsonresult = urlresult.read() # get the JSON
parsedjson = json.loads(jsonresult) # put parsed JSON into dictionary
return parsedjson
也许checkIP
中的调用代码应改为使用try
/ except
,例如如果服务器指示您运行得太快,请在睡眠后重试。
(在没有授权令牌的情况下,您似乎正在使用此服务的免费版本,无论如何,它可能无法得到任何保证。也可能正在考虑使用其推荐的库-我没有看过更详细地讲,但我想它至少会更好地了解服务器端错误时的行为,几乎可以肯定,它也是Pythonic的,至少在某种意义上,您不应重新发明已经存在的东西存在。)