Django在web页面上返回none

2024-03-28 11:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Django中运行这个函数时,我的输出是none。news()函数有什么问题?你知道吗

代码:

import feedparser
from django.http import HttpResponse

def news():
    YahooContent = feedparser.parse ("http://news.yahoo.com/rss/")
    for feed in YahooContent.entries:
        print feed.published
        print feed.title
        print feed.link + "\n"
    return

def html(request):
    html = "<html><body> %s </body></html>" % news()
    return HttpResponse(html)

错误: 网页显示无


Tags: django函数importnonehttpreturndefhtml
2条回答

您正在打印结果,而不是返回结果。实际上,return语句将返回None,就像所有没有return语句的方法一样。你知道吗

您应该在方法本身中构建字符串,如下所示:

def html(request):
    head = '<html><body>'
    foot = '</body></html>'
    entries = []
    for entry in feedparser.parse("http://news.yahoo.com/rss/").entries:
        entries.append('{}<br />{}<br />{}<br />'.format(entry.published,
                                                   entry.title, entry.link))
    return HttpResponse(head+''.join(entries)+foot)

Can you explain your code a little bit?

假设您有一个“条目”列表,如下所示:

entries = [a, b, c]

每个条目都有一个.published.title.link属性,您希望在HTML中打印为列表。你知道吗

您可以通过循环并使用print语句轻松完成此操作:

print('<ul>')
for entry in entries:
    print('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
print('</ul>')

但是,我们在这里需要的是将这些数据作为HTML响应发送到浏览器。我们可以通过用不断添加的字符串替换print来构建HTML字符串,如下所示:

result = '<ul>'
for entry in entries:
    result += '<li>{0.published} - {0.title} - {0.link}</li>'.format(entry)
result += '</ul>'

这将起作用,但是inefficient and slow,最好在列表中收集字符串,然后将它们连接在一起。这就是我最初的回答:

result = ['<ul>']
for entry in entries:
    result.append('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
result.append('</li>')

然后我用一个页眉和一个页脚将它们连接起来,然后用空格将列表中的每个字符串组合起来,作为响应返回:

 return HttpResponse('<html><body>'+''.join(result)+'</body></html>')

显然,news()方法不返回任何内容。。你知道吗

正确的方法应该是:

def news():
    YahooContent = feedparser.parse ("http://news.yahoo.com/rss/")
    result = ''
    for feed in YahooContent.entries:
        result += feed.published + '\n'
        result += feed.title + '\n'
        result += feed.link + "\n"
    return result

def html(request):
    html = "<html><body> %s </body></html>" % news()
    return HttpResponse(html)

相关问题 更多 >