如何使我只需要引用一次api密钥?

2024-04-20 04:14:12 发布

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

我正在自学如何使用python和django访问googleplacesapi,在附近搜索不同类型的健身房。你知道吗

我只学到了如何在本地构建的数据库中使用python和django。你知道吗

我为他们写了一个完整的获取请求四个不同的搜索我正在做。我查了一些例子,但没有一个对我有用。你知道吗

allgyms = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
all_text = allgyms.text
alljson = json.loads(all_text)

healthclubs = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&keyword=healthclub&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
health_text = healthclubs.text
healthjson = json.loads(health_text)

crossfit = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&keyword=crossfit&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
cross_text = crossfit.text
crossjson = json.loads(cross_text)

我真的很想在正确的方向上指出如何有api键引用只有一次,而改变关键字。你知道吗


Tags: texthttpscomapijsongettypeplace
1条回答
网友
1楼 · 发布于 2024-04-20 04:14:12

为了更好的可读性和重用性,可以尝试这样做

BASE_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
LOCATION = '38.9208,-77.036'
RADIUS = '2500'
TYPE = 'gym'
API_KEY = 'AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg'
KEYWORDS = ''

allgyms = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&key='+API_KEY) all_text = allgyms.text 
alljson = json.loads(all_text)

KEYWORDS = 'healthclub'
healthclubs = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&keyword='+KEYWORDS+'&key='+API_KEY) 
health_text = healthclubs.text 
healthjson = json.loads(health_text)


KEYWORDS = 'crossfit'
crossfit = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&keyword='+KEYWORDS+'&key='+API_KEY) 

cross_text = crossfit.text 
crossjson = json.loads(cross_text)

正如V-R在评论中所建议的那样,您可以更进一步地定义函数,从而使事情更可重用,从而允许您在应用程序的其他地方使用该函数

功能实现

def makeRequest(location, radius, type, keywords):
    BASE_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
    API_KEY = 'AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg'
    result = requests.get(BASE_URL+'location='+location+'&radius='+radius+'&type='+type+'&keyword='+keywords+'&key='+API_KEY)
    jsonResult = json.loads(result)
    return jsonResult

函数调用

json = makeRequest('38.9208,-77.036', '2500', 'gym', '')

如果有问题,请告诉我

相关问题 更多 >