Python 3.x Typeerror:新闻对象不可编辑
我正在尝试从新闻api获取新闻,我已将函数设置为返回一个新闻结果数组。我想显示新闻的显示模板中出现错误Python 3.x Typeerror:新闻对象不可编辑,python-3.x,Python 3.x,我正在尝试从新闻api获取新闻,我已将函数设置为返回一个新闻结果数组。我想显示新闻的显示模板中出现错误 def getNews(): ''' function that fetches all news ''' with urllib.request.urlopen(news_url+'281dbdc2e10e4a6ab51a9a27a614c146') as me: news_data = me.read() news_response = json.load
def getNews():
'''
function that fetches all news
'''
with urllib.request.urlopen(news_url+'281dbdc2e10e4a6ab51a9a27a614c146') as me:
news_data = me.read()
news_response = json.loads(news_data)
all_news = None
if news_response['articles']:
all_news_list = news_response['articles']
all_news_data = process_news(all_news_list)
return all_news
def process_news(news_list):
all_news = []
for news in news_list:
author = news.get('author')
title = news.get('title')
description = news.get('description')
url = news.get('url')
urlToImage = news.get('urlToImage')
publishedAt = news.get('publishedAt')
if author:
news_object = Article(author,title,description,url,urlToImage,publishedAt)
all_news.append(news_object)
return all_news
@makozaki给定代码,
getNews
将始终返回None
all\u news
在返回之前不会重新分配。您必须了解all\u news
在这两种方法中都是局部变量。您必须从getNews
返回all\u news\u data
,这是process\u news
的实际输出。
@main.route('/')
def index():
news = getNews()
title = "All News"
return render_template('index.html',news=news,title=title)
{% for myNews in news %}
{% endfor %}