Python?Django教程之實現(xiàn)新聞應用程序
Django是一個用Python編寫的高級框架,它允許我們創(chuàng)建服務器端Web應用程序。在本文中,我們將了解如何使用Django創(chuàng)建新聞應用程序。
我們將使用新聞 API 并從 API 中獲取所有頭條新聞。 在命令提示符或終端中執(zhí)行以下步驟:

使用文本編輯器打開新聞項目文件夾。目錄結構應如下所示

在新聞應用程序中創(chuàng)建一個“模板”文件夾,并在 settings.py
settings.py

在 views.py –在視圖中,我們創(chuàng)建了一個名為 index 的視圖,該視圖接受請求并將 html 呈現(xiàn)為響應。首先,我們從新聞客戶導入新聞資本。
# 導入 api
from django.shortcuts import render
from newsapi import NewsApiClient
# 在此處創(chuàng)建視圖。
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})
在模板文件夾中創(chuàng)建index.html。
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" 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">
在我們的網(wǎng)站上獲取最新消息
</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>現(xiàn)在將視圖映射到 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),
]到此這篇關于Python Django教程之實現(xiàn)新聞應用程序的文章就介紹到這了,更多相關Python Django新聞應用程序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用post及get方式提交數(shù)據(jù)的實例
今天小編就為大家分享一篇關于Python使用post及get方式提交數(shù)據(jù)的實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Pytorch在dataloader類中設置shuffle的隨機數(shù)種子方式
今天小編就為大家分享一篇Pytorch在dataloader類中設置shuffle的隨機數(shù)種子方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Django REST Framework 分頁(Pagination)詳解
這篇文章主要介紹了Django REST Framework 分頁(Pagination)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11
Pytorch反向傳播中的細節(jié)-計算梯度時的默認累加操作
這篇文章主要介紹了Pytorch反向傳播中的細節(jié)-計算梯度時的默認累加操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

