如何使用 google places with python 和 flask 获取附近的地方

how to get nearby places using google places with python and flask

我正在尝试通过 python 和 flask

使用 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
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)

然后变量 nameratinglocation 将在模板中作为 {{name}}{{rating}}{{location}} 访问。

但是,您布置 for 循环的方式意味着第一次到达 return 语句时,它将停止循环并 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 %}