python
主页 > 脚本 > python >

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

2022-10-25 | 佚名 | 点击:

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

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

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

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

settings.py

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

# 导入 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。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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

1

2

3

4

5

6

7

8

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),

]

原文链接:https://juejin.cn/post/7156192767054446629
相关文章
最新更新