Python Django教程之实现新闻应用程序

Django是一个用Python编写的高级框架,它允许我们创建服务器端Web应用程序。在本文中,我们将了解如何使用Django创建新闻应用程序。

我们将使用新闻 API 并从 API 中获取所有头条新闻。 在命令提示符或终端中执行以下步骤:

Python Django教程之实现新闻应用程序

使用文本编辑器打开新闻项目文件夹。目录结构应如下所示

Python Django教程之实现新闻应用程序

在新闻应用程序中创建一个“模板”文件夹,并在 settings.py

settings.py

Python Django教程之实现新闻应用程序

在 views.py –在视图中,我们创建了一个名为 index 的视图,该视图接受请求并将 html 呈现为响应。首先,我们从新闻客户导入新闻资本。

# 导入 api
from django.shortcuts import render
from newsapi import NewsApiClient

# 在此处创建视图。
def index(request):
	
	newsapi = NewsApiClient(api_key =\'YOURAPIKEY\')
	top = newsapi.get_top_headlines(sources =\'techcrunch\')

	l = top[\'articles\']
	desc =[]
	news =[]
	img =[]

	for i in range(len(l)):
		f = l[i]
		news.append(f[\'title\'])
		desc.append(f[\'description\'])
		img.append(f[\'urlToImage\'])
	mylist = zip(news, desc, img)

	return render(request, \'index.html\', context ={\"mylist\":mylist})

模板文件夹中创建index.html。

<!DOCTYPE html>
<html lang=\"en\" dir=\"ltr\">
<head>
	<meta charset=\"utf-8\">
	<title></title>

<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"external nofollow\"  integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">
<!-- Optional theme -->
</head>
<body>
	<div class=\"jumbotron\" style=\"color:black\">

	<h1 style =\"color:white\">
在我们的网站上获取最新消息
	</h1>

	</div>


	<div class=\"container\">
	{% for new, des, i in mylist %}
			<img src=\"{{ i }}\" alt=\"\">
			<h1>news:</h1> {{ new }}
			{{ value|linebreaks }}

			<h4>description:</h4>{{ des }}
			{{ value|linebreaks }}

	{% endfor %}
	</div>

</body>
</html>

现在将视图映射到 urls.py

from django.contrib import admin
from django.urls import path
from newsapp import views

urlpatterns = [
path(\'\', views.index, name =\'index\'),
	path(\'admin/\', admin.site.urls),
]
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容