为什么会出现此错误? TypeError:必须为str,而不是NoneType

时间:2019-02-04 01:24:56

标签: python-3.x discord.py

我正在尝试使用geoip2库来获取ip地址的位置,但是我一直收到类型错误。

以前曾经工作过的代码,不确定发生了什么。

@client.command(name="iplocation")
async def ip_location(*,ip):
    try:
        reader = geoip2.database.Reader('GeoLite2-City.mmdb')
        response = reader.city(ip)

        await client.say("Country: " + response.country.iso_code)
        await client.say("City: " + response.subdivisions.most_specific.name)
        await client.say("Postal Code: " + response.postal.code)
        await client.say("Latitude: " + str(response.location.latitude))
        await client.say("Longitude: " + str(response.location.longitude))
        reader.close()
     except geoip2.errors.AddressNotFoundError:
         await client.say("The Address: " + ip + " Is not in the database")
     except ValueError:
         await client.say(ip + " Does not appear to be an IPv4 or IPv6 address.")

我希望

国家/地区:美国 城市:纽约 邮政编码10453 纬度:1.2931 经度:103.8558

这只是一个例子。

我的错误:

Traceback (most recent call last):
  File "/home/c0deninja/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "discordbot2.py", line 116, in ip_location
    await client.say("City: " + response.subdivisions.most_specific.name)
TypeError: must be str, not NoneType

1 个答案:

答案 0 :(得分:1)

要从中提取数据的数据集,必须在没有城市集的情况下使用None作为一种类型。在这种情况下,错误消息是一个很好的提示。您必须通过执行您说的转换来允许它将None用作字符串,或者测试None并使用空白字符串代替实际的城市名称。

在任何您使用的数据集中没有设置字符串的情况下,都可能发生此错误。

File "discordbot2.py", line 116, in ip_location
    await client.say("City: " + response.subdivisions.most_specific.name)
TypeError: must be str, not NoneType