Django教程-Django新闻应用
Django教程-Django新闻应用
gh_1d7504e4dee1
回复:python,领取Python面试题。分享Python教程,Python架构师教程,Python爬虫,Python编程视频,Python脚本,Pycharm教程,Python微服务架构,Python分布式架构,Pycharm注册码。
资源分享
代码部分:
# 导入所需的API
from
django.shortcuts
import
render
from
newsapi
import
NewsApiClient
# 在这里创建我们的视图。
def
index
(req)
:
newsapi = NewsApiClient(api_key=
’YOURAPIKEY’
)
top = newsapi.get_top_headlines(sources=
’techcrunch’
)
l = top[
’articles’
]
descri = []
news = []
img = []
for
i
in
range(len(l)):
fj = l[i]
news.append(fj[
’title’
])
descri.append(fj[
’description’
])
img.append(fj[
’urlToImage’
])
mylistin = zip(news, descri, img)
return
render(req,
’index.html’
, context={
"mylist"
: mylistin})
在templates文件夹中创建一个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"
integrity
=
"sha384-ggOysewffegv3Xipma34MD+dH/1frf84/j6cY/iJTQerg4e5y56yu59JvoRxT2MZw1T"
crossorigin
=
"anonymous"
>
<!-- 可选主题 -->
</
head
>
<
body
>
<
div
class
=
"megatron"
style
=
"color:black"
>
<
h1
style
=
"color:white"
>
在我们的网站上找到最新的新闻。
</
h1
>
</
div
>
<
div
class
=
"container"
>
{% for new, des, i in mylistin %}
<
img
src
=
"{{ i }}"
alt
=
""
>
<
h1
>
新闻:
</
h1
>
{{ new }}
{{ des|linebreaks }}
<
h4
>
描述:
</
h4
>
{{ des }}
{{ des|linebreaks }}
{% endfor %}
</
div
>
</
body
>
</
html
>
现在将视图映射到urls.py:
from
django.contrib
import
admin126459646
# 导入urls
from
django.urls
import
path
from
newsapp
import
views
urlpatterns = [
path(
’’
, views.index, name=
’index’
),
path(
’admin126459646/’
, admin126459646.site.urls),
]
输出:
-
Python+Excel 报表自动化指南
-
Django教程-如何使用 F() 表达式
-
拒写赌博程序被虐待?全身损伤达88%
-
2023年血糖新标准公布,不是3.9-6.1,快来看看你的血糖正常吗? 2023-02-07
-
2023年各省最新电价一览!8省中午执行谷段电价! 2023-01-03
-
GB 55009-2021《燃气工程项目规范》(含条文说明),2022年1月1日起实施 2021-11-07
-
PPT导出高分辨率图片的四种方法 2022-09-22
-
2023年最新!国家电网27家省级电力公司负责人大盘点 2023-03-14
-
全国消防救援总队主官及简历(2023.2) 2023-02-10
-
盘点 l 中国石油大庆油田现任领导班子 2023-02-28
-
我们的前辈!历届全国工程勘察设计大师完整名单! 2022-11-18
-
关于某送变电公司“4·22”人身死亡事故的快报 2022-04-26
