我编写了一个用于调用Google Places API的函数,但我想做得更好。具体来说,我怀疑在函数调用中有更好的方法来处理可选参数,例如location
和radius
。如何在不编写可选参数的所有可能排列的情况下动态构造自己的url?
def get_data(query,api_key,radius=None,location=None):
if location==None and radius==None:
url="https://maps.googleapis.com/maps/api/place/textsearch/json?query=%s&fields=name,formatted_address,opening_hours,price_level,rating&key=%s" % (query,api_key)
elif location is not None:
url="https://maps.googleapis.com/maps/api/place/textsearch/json?query=%s&location=%s&fields=name,formatted_address,opening_hours,price_level,rating&key=%s" % (query,location, api_key)
elif location is not None and radius is not None:
url="https://maps.googleapis.com/maps/api/place/textsearch/json?query=%s&location=%s&radius=%s&fields=name,formatted_address,opening_hours,price_level,rating&key=%s" % (query,location,radius, api_key)
----Snip-----
答案 0 :(得分:3)
我认为这段代码可以解决您的问题:
base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {
'key': 'api_key',
'fields':'name,formatted_address,opening_hours,price_level,rating',
'query' : query
}
if location is not None:
params['location'] = location
if radius is not None:
params['radius'] = radius
url = base_url + urllib.urlencode(params)