首页 > 解决方案 > 在 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 语句上,但无论我把它放在哪里,我都会遇到同样的问题。

如果有人可以分享我如何返回所需数量的对象而不是第一个对象,我将不胜感激。

标签: pythonfor-loopflask

解决方案


您上面的代码正在返回一个包含单个项目的字典,它似乎应该返回一个此类字典的列表。尝试这样的事情:

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 

推荐阅读