Python ip(';me';)在本地工作,但不在heroku上工作

Python ip(';me';)在本地工作,但不在heroku上工作,python,django,heroku,geocoder,Python,Django,Heroku,Geocoder,我正在使用Django,需要获取用户的当前位置,因此我使用geocoder.ip('me')。它在本地运行良好,但在我将其部署到Heroku上之后,它似乎不起作用。是因为IP地址还是类似的原因?我怎样才能修好它?或者是否有其他更容易访问views.py中用户当前位置的方法?多谢各位 我找到了获取ip地址的方法,但我不知道如何真正获取ip地址,以便在代码的其他部分使用它 def get_client_ip(self,request): x_forwarded_for = request.M

我正在使用Django,需要获取用户的当前位置,因此我使用
geocoder.ip('me')
。它在本地运行良好,但在我将其部署到Heroku上之后,它似乎不起作用。是因为IP地址还是类似的原因?我怎样才能修好它?或者是否有其他更容易访问views.py中用户当前位置的方法?多谢各位

我找到了获取ip地址的方法,但我不知道如何真正获取ip地址,以便在代码的其他部分使用它

def get_client_ip(self,request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

class RecommendView(generic.ListView):
    template_name = 'event/recommend.html'
    context_object_name = 'recommend_event_list'
    today = datetime.now().date()
    end = today + timedelta(7)
    time_start = datetime.combine(today, time())
    time_end = datetime.combine(end, time())
    ip = get_client_ip()
    myloc = geocoder.ip(ip,key='my_key')
    def get_queryset(self):
        rec=Event.objects.filter(post_date__range=(self.time_start, self.time_end))
        for event in rec:
            g = geocoder.mapbox(event.address, key='my_key')
            R = 6373.0
            lat1 = math.radians(self.myloc.lat)
            lon1 = math.radians(self.myloc.lng)
            lat2 = math.radians(g.lat)
            lon2 = math.radians(g.lng)

            dlon = lon2 - lon1
            dlat = lat2 - lat1
            a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2

            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
            dis = R * c
            if dis>20:
                rec=rec.exclude(address=event.address)
        return rec.order_by('-post_date')

你说的“不工作”是什么意思?你能更具体地说明你遇到的错误吗?请看我在我的所有对象中循环,并去掉那些远离用户“我”的对象。一些对象应该打印出来,因为它们离用户很近。在本地,它还剩下两个,但在我部署到heroku之后,它们都没有了。所以我认为这是因为ip地址,但我不确定这是否是问题所在。@Selcuk谢谢!但我对网络编码非常陌生,我知道问题是什么,但不确定应该如何重写代码。ip(“x-forwarded-for”)似乎也不起作用。
geocoder
文档明确指出,您应该传递
'me'
或实际ip地址。因此,您应该从
X-Forwarded-For
头中提取IP地址,并将该值传递给
.ipinfo()
方法。