python - 在 Flask REST API Python 中显示数据列表
问题描述
在我的 REST API 中,我有以下代码
i = 0
for item in similar_items:
name= main.get_name_from_index(item [0])
url = main.get_url_from_index(item [0])
category = main.get_categories_from_index(item [0])
if (name!= None):
return {'Name': name, 'Category': category, 'URL': url }, 200 # return data and 200 OK code
i = i + 1
if i > 20:
break
这本质上是打算遍历similar_items
并打印出前 20 个,但目前它只发送第一个的 JSON 对象。我相信问题出在 return 语句上,但无论我把它放在哪里,我都会遇到同样的问题。
如果有人可以分享我如何返回所需数量的对象而不是第一个对象,我将不胜感激。
解决方案
您上面的代码正在返回一个包含单个项目的字典,它似乎应该返回一个此类字典的列表。尝试这样的事情:
i = 0
results = [] # prepare an empty results list
for item in similar_items:
name= main.get_name_from_index(item [0])
url = main.get_url_from_index(item [0])
category = main.get_categories_from_index(item [0])
if (name!= None):
results.append({'Name': name, 'Category': category, 'URL': url }) # add the current item into the results list
i = i + 1
if i > 20: # NB if you want 20 items this should be >= not just > :-)
return results, 200 # return data and 200 OK code
break
推荐阅读
- html - 在邮件中测试时如何使用网格布局修复电子邮件模板响应问题
- python - 选择带有 Selenium 变量的复选框
- mysql - 从mysql中的csv字符串生成字符串的索引/位置
- python - Python Discord 机器人嵌入
- html - 我可以在 Spring Boot 环境中使用 ckEditor 使用 Thymeleaf 吗?
- swift - AF 没有成员“responseDecodable”与路由器
- mpandroidchart - 尝试在空对象引用 BarChart 上调用虚拟方法 'com.github.mikephil.charting.charts.BarChart.setMarker'
- c# - 使用 Cudafy 获取总 GPU 内存。返回最大 ulong 值
- python - 如何在 Python 中循环并增加 Excel 工作簿公式中的行?
- text - 允许从选定文件创建项目的 Macos 文本编辑器