![](/img/trans.png)
[英]jinja2.exceptions.UndefinedError: object has no attribute
[英]Code stopped working. Gives me a `jinja2.exceptions.UndefinedError: 'list object' has no attribute 'items'` error
我正在為我的網絡應用程序使用 spotify 的 API。 我創建了一個搜索欄,根據 Spotify 的要求詢問查詢和該查詢的類型(例如曲目、專輯、藝術家)。 搜索專輯的代碼運行良好,直到幾個小時前它停止並開始給我以下錯誤jinja2.exceptions.UndefinedError: 'list object' has no attribute 'items'
終端指出問題出在以下行{% for k, v in value.items() %}
應該注意的是,我沒有更改代碼中的任何內容,正如我提到的那樣,它工作得很好,我繼續返回 Spotify 的控制台檢查我收到的數據以及我的代碼中是否存在邏輯錯誤,但我似乎找不到。 實際上,我在尋找藝術家時面臨着同樣的問題。 但那是另一個問題。 現在,問題是我搜索專輯。
為了更好地了解收到的數據,您可以查看 Spotify 的搜索控制台: https : //developer.spotify.com/console/get-search-item/
幫助將不勝感激。 謝謝。
<section class="wrapper">
<div class="search-res">
<h1 class="header">{{query}}</h1>
<div class="row">
<div class="records" id="tracks">
{% set info = [] %}
{% if q_type == "album" %}
{% for record in results['albums']['items'] %}
{% for key, value in record.items() %}
{% if key == "artists" %}
{% for k, v in value.items() %}
{% if k == "name" %}
{{info.append(v) or ""}}
{% endif %}
{% endfor %}
{% endif %}
{% if key == "name" %}
{{info.append(value)}}
{% endif %}
{% if key == "id" %}
{{info.append(value)}}
{% endif %}
{% if key == "external_urls" %}
{% for k, v in value.items() %}
{% if k == "spotify" %}
{{info.append(v) or ""}}
{% endif %}
{% endfor %}
{% endif %}
{% if key == "images" %}
{% for k, v in value[1].items() %}
{% if k == "url" %}
{{info.append(v) or ""}}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
{{info}}
{% endif %}
</div>
</div>
</div>
</section>
字典有一個函數items()
。 如果你有這樣的字典{'a': 'A', 'b': 'B'}
, dic.items() 會給你一個元組列表[('a', 'A'), ('b', 'B')]
。
這個函數幫助我們用鍵和值迭代字典。
您的錯誤是'list object' has no attribute 'items'
。 這表明value
是一個列表,而不是一個字典。 由於您正在為列表調用字典函數 (items()),因此您收到此錯誤。
您必須逐行調試才能更好地理解。 刪除此行之后的所有內容。
{% for k, v in value.items() %}
只需打印value
即可檢查數據類型。 我希望它是一個清單。 只需在下面添加此行並檢查輸出。
{{ value }}
但是由於您直接從他們的網站復制了此代碼,因此代碼中不應有任何錯誤。 無論如何,只需檢查如上所述的數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.