簡體   English   中英

顯示 Flask REST API ZA7F5F35426B927411FC9231BZ56 中的數據列表

[英]Displaying a List of Data from in 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 object。 我相信問題出在 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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM