【问题标题】:Passing IP address isn't working in a Function, unless I explicitly mention it除非我明确提及,否则传递 IP 地址在函数中不起作用
【发布时间】:2022-06-20 00:18:34
【问题描述】:

我正在尝试使用“GeoIP2-City.mmdb”文件查找给定 IP 地址的国家/地区名称。

例如:IP:24.171.221.56,我需要获取“波多黎各”。但是当我在函数中传递 IP 地址时,这不起作用。

ipa = ['24.171.221.56']

def country(ipa, reader):
    try:
        response = reader.city(ipa)
        response = response.country.name
        return response
    except:
        return 'NA'

country(ipa, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))

'NA'

但是,如果我在函数中使用实际的 IP 地址,它会返回“波多黎各”

ipa = ['24.171.221.56']

def country(ipa, reader):
    try:
        response = reader.city('24.171.221.56')
        response = response.country.name
        return response
    except:
        return 'NA'

country(ipa, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))

'Puerto Rico'

有人可以帮忙吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    首先,您需要将 ip 作为字符串而不是列表传递,因为您的函数仅旨在返回一个 IP 的位置:

    ip = '24.171.221.56'
    

    其次,应该是ip,而不是ipa。您的函数参数必须与您在其中使用的变量匹配,并且您发送的参数必须与您在外部定义的参数匹配。最好将它们全部标准化为ip

    ip = '24.171.221.56'
    
    def country(ip, reader):
        try:
            response = reader.city(ip)
            response = response.country.name
            return response
        except:
            return 'NA'
    
    country(ip, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))
    

    如果您打算为多个 ip 执行此操作,您可以在列表中定义它们,但是您必须为列表中的每个项目调用一次函数:

    reader=geoip2.database.Reader('GeoIP2-City.mmdb')
    ips=['24.171.221.56','24.171.221.57']
    for ip in ips:
        country(ip, reader=reader)
    

    【讨论】:

      【解决方案2】:

      你可以试试下面的代码sn-p。

      代码:

      import geoip2.database as ip_db
      
      
      ip_list = ['24.171.221.56', '81.212.104.158', '90.183.159.46']
      
      def country(ip_list, reader):
        country_dict = {}
        for ip in ip_list:
          try:
              response = reader.city(ip)
              country = response.country.name
              country_dict[ip] = country
          except:
              country_dict[ip] = 'NA'
        return country_dict
      
      print(country(ip_list, reader=ip_db.Reader('GeoIP2-City.mmdb')))
      

      输出:

      {'24.171.221.56': 'Puerto Rico', '81.212.104.158': 'Turkey', '90.183.159.46': 'Czechia'}
      

      【讨论】:

        【解决方案3】:

        您将列表传递给函数,因此您需要执行 ip[0] 或在函数内部更改以使用列表

        【讨论】:

          【解决方案4】:

          排队:

          response = reader.city(ip)
          

          ip 未定义。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-05-30
            • 1970-01-01
            • 2020-01-22
            • 1970-01-01
            • 2018-04-13
            • 1970-01-01
            • 2015-12-29
            • 1970-01-01
            相关资源
            最近更新 更多