繁体   English   中英

django在网页上不返回任何内容

[英]django returns none on web page

当我在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)

错误:网页显示无

您正在打印结果,而不是返回结果。 实际上,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)

您能解释一下您的代码吗?

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

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>'

这将起作用,但是效率低下且速度慢 ,最好将字符串收集到列表中,然后将它们连接在一起。 这是我在原始答案中所做的:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM