2015-09-26 30 views
0

這些是我使用IP進行國家檢測的函數。'str'對象在檢索請求時沒有屬性'META'功能.META

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'錯誤的,如果我在get_ip_address功能打印request.META,其打印控制檯沒有任何錯誤。這裏有什麼問題?

+0

顯然你傳遞一個字符串,而不是請求對象。 – jonrsharpe

+1

你應該真的研究異常的*完整回溯*(並且*總是*在提問時發佈它)。我能夠在這裏精神上追蹤這個問題,但是你的回溯會直接告訴你這個字符串是通過'geoip_country()'來傳遞的。 –

+1

注意:'user_location =(ip_country)'和'user_location = ip_country'是一樣的。你可以使用'return ip_country'。你的意思是返回一個*元組*嗎?在這種情況下,你錯過了一個逗號; '返回ip_country,' –

回答

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) 
+0

謝謝!這真是一個愚蠢的錯誤,我正在做 –

相關問題