python程序中添加ip识别提升openai账号的安全性
最近封号风波好像波及了很多人,我自己注册的账号都没有问题的,以前我调用api都没有特别在意节点的问题,账号目前还在,我认为调用api不是太大的问题。看到今天有很多人因为节点的问题被封号。我决定给自己的程序添加一个ip识别,利用request和geoip模块提前判断网络状况和ip地址,防止自己使用不合适的ip来调用api。
以下是一个相关实例,希望对使用python调用openai api的朋友有所帮助。其中
GeoLite2-City.mmdb文件需要自己手动下载,下载方式可以问newbing。

import requests
import geoip2.database
# ip地址归属列表
# ipaddresslist = ['China','United States','Hong Kong','Singapore','Japan','Australia','Germany','France','South Korea','Taiwan','India', 'Russia', 'Turkey', 'New Zealand']
ipuseopenailist=['United States','Australia','Germany','France','India','Turkey','New Zealand']
ipbanopenailist=['China','Hong Kong','Singapore','Japan','South Korea','Taiwan','Russia']
try:
response = requests.get('https://api.ipify.org')
client_ip = response.text
# print(client_ip)
# Replace YOUR_DATABASE_FILE with the path to your GeoLite2-City.mmdb file
reader = geoip2.database.Reader(r'F:\BaiduNetdiskWorkspace\zahuo\自己的兴趣\USEAI\GeoLite2-City\GeoLite2-City.mmdb')
response = reader.city(client_ip)
countryname = response.country.name
reader.close()
if countryname in ipuseopenailist:
print(countryname,": 可以使用openai")
else:
print(countryname,": 不可以使用openai")
# print(response.country.name)
# print(response.subdivisions.most_specific.name)
# print(response.city.name)
except requests.exceptions.RequestException as e:
print("网络连接失败:", e)