我正在点击黑客新闻API here,想要了解我通过JSON获得的每个帖子的详细信息。我想把这个JSON发送到我的React前端。
此请求需要很长时间。发送回复需要做什么?
@app.route('/api/posts')
def get_posts():
r = requests.get('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty')
data = r.text
jsonData = []
for post in data:
r = requests.get('https://hacker-news.firebaseio.com/v0/item/'+post+'.json?print=pretty')
r.text
jsonData.append(r.text)
jsonData = jsonify(jsonData)
print jsonData
return jsonData
答案 0 :(得分:3)
您正在查询json API并将响应视为文本:
r = requests.get('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty')
data = r.text
因此,r.text
将是一个字符串“[1234,1235,1236]”,而不是一个整数列表。
所以当你在for post in data
中迭代时,你正在做的就是获得每个角色:
for post in data:
print(post)
会给你:
[
1
2
3
4
,
...etc
所以你基本上要查询数百个无效帖子的黑客新闻API,而不是数十个实际的帖子。您应该使用内置于请求中的json功能将json
视为json-:data = r.json()
这将为您提供一个迭代的数字列表 - 您还需要更改连接数据以制作网址字符串的错误方式(使用.format
)。
答案 1 :(得分:1)
requests
有一个.json()
方法,您应该使用该方法将JSON数组字符串转换为python列表。
In [1]: import requests
In [2]: r = requests.get('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty')
In [3]: jsonData = r.json()
In [4]: for data in jsonData[:5]:
... print data
...:
12102489
12100796
12101060
12097110
12094366
如另一个答案中所述,for post in data:
将为您提供HTTP响应中的单个字符。换句话说,想想for post in "abc":
会给你什么。
该页面需要很长时间才能加载
那是因为您正在针对所有这些单个字符运行新查询。