首页 > 解决方案 > 如何使用带有 python 和烧瓶的谷歌地方获取附近的地方

问题描述

我正在尝试使用带有 python 和烧瓶的 googleplaces 去附近的地方

我收到此错误:(UnboundLocalError:分配前引用的局部变量“place_name”)

这是我的代码:

@app.route('/Search', methods=['POST', 'GET'])
@login_required
def Search():
    if request.method == 'POST':
        query_result = google_places.nearby_search(
            lat_lng={'lat':31.7917, 'lng' : 7.0926},
            radius=500,
            types=[types.TYPE_SHOPPING_MALL] or [types.TYPE_STORE])`

        if query_result.has_attributions:
            print(query_result.html_attributions)

        for place in query_result.places:
            place.get_details()
            place_name = place.name
            print(place.name)
            place_rating = place.rating
            print(place.rating)
            place_location = place.get_location
            print(place.get_location)
            for photo in place.photos:
                photo.get(maxheight=500, maxwidth=500)
                photo.mimetype
                photo.url
                photo.filename
                photo.data
            return render_template('Search.html', place_name, place_rating, place_location)
    else:
        return render_template('Search.html')```


#Note: i am new to python in general

标签: pythonflaskgoogle-places

解决方案


return render_template('Search.html', place_name, place_rating, place_location)

以上不是有效的语法。当您将详细信息传递给模板时,您需要这样做:

return render_template('Search.html', name = place_name,
                        rating = place_rating, location = place_location)

变量name,rating然后location可以在模板中作为{{name}},{{rating}}和访问{{location}}

但是,布局 for 循环的方式意味着第一次到达 return 语句时,它将停止循环并返回带有这些变量的模板。

也许这就是你想要的,但你可能希望传递query_result给模板,并在模板中实现一个 Jinja2 for 循环,以打印出各个地方的详细信息。您将删除 for 循环并将整个块替换为:

return render_template('Search.html', all_places = query_result)

然后在模板中类似:

{% if all_places %}
{% for place in all_places %}
    <p><b>{{place.name}}</b> has a rating of <u>{{place.rating}}</u></p>
{% endfor %}
{% else %}
    <p>No places found.</p>
{% endif %}

推荐阅读