这些是我使用IP进行国家检测的功能。
from unipath import Path
import pygeoip
# Country Detection
def get_ip_address(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def geoip_country(request):
path = Path(__file__).ancestor(3)+"/scripts/notes/custom_packages/geoip/GeoIP.dat"
geoDetect = pygeoip.GeoIP(path)
return geoDetect.country_code_by_addr(get_ip_address(request))
def get_user_location(request):
ip = get_ip_address(request)
ip_country = geoip_country(ip)
user_location = (ip_country)
return user_location
当我通过传递请求对象在视图中调用此函数时:
get_user_location(request)
我收到'str' object has no attribute 'META'
错误,好像我在request.META
函数中打印get_ip_address
,它在控制台中打印没有任何错误。这里有什么问题?
答案 0 :(得分:1)
您正在将ip
参数传递给geoip_country()
:
ip = get_ip_address(request)
ip_country = geoip_country(ip)
但您的geoip_country()
函数需要request
:
def geoip_country(request):
然后再将get_ip_address()
传递给:
return geoDetect.country_code_by_addr(get_ip_address(request))
更改geoip_country()
功能以改为ip
:
def geoip_country(ip):
path = Path(__file__).ancestor(3)+"/scripts/notes/custom_packages/geoip/GeoIP.dat"
geoDetect = pygeoip.GeoIP(path)
return geoDetect.country_code_by_addr(ip)