【发布时间】:2017-12-01 16:21:37
【问题描述】:
我正在开发一个网络应用程序,它可以显示用户附近的事件。我有下面的代码可以工作,但给出结果的速度很慢。 我想知道是否有办法让它更快。目前仅计算 5 个事件的距离大约需要 3 秒。这是我的代码 sn-p。
@app.route('/events')
def events():
events = Post.query.filter_by(event=True, trivia=False, approved=True, featured=False).order_by(Post.datetime.asc()).all()
geolocator = Nominatim()
if current_user.state_1 != None:
res_state = current_user.state_1
else:
res_state = ','
user_city = geolocator.geocode(current_user.city_1 + ' ' + res_state + ' ' + current_user.residence)
user_city = (user_city.latitude, user_city.longitude)
events_near = []
for event in events:
if event.address_2 != None:
address_2 = event.address_2+','
else:
address_2 = ','
if event.state != None:
state = event.state+','
else:
state = ','
if event.zip_code != None:
zip_code = event.zip_code+'.'
else:
zip_code = '.'
location = geolocator.geocode(event.address_1+',' + ' ' + address_2 + ' ' + event.city+',' + ' ' + state + ' ' + zip_code + ' ' + event.country )
location = (location.latitude, location.longitude)
distance = geopy.distance.vincenty(user_city, location).miles
if distance < dist:
events_near.append(event)
return render_template('events.html', events_near=events_near)
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
你知道哪些行需要这么长时间吗?
-
@Atto 我不太确定是哪一行,但我相信那些具有地理定位的行,其中 lat 和 lng 是为地址计算的。
-
能否举例说明
user_city = geolocator.geocode(current_user.city_1 + ' ' + res_state + ' ' + current_user.residence)行中的变量可能是什么? -
@Atto Alla 类似于 user_city = geolocator.geocode('Oakland, California, United States')。它基本上是获取用户所在城市的纬度和经度。
-
不幸的是,这个功能似乎很慢(因为它需要查询互联网),所以你可以做的不多