ip(“me”)在本地工作,但不在heroku上工作

2024-10-02 16:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我在How do I get user IP address in django?中找到了获取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')

Tags: keyselfipeventforgettimeaddress