首页 > 行业资讯 > Django教程-Django新闻应用

Django教程-Django新闻应用

时间:2023-08-27 来源: 浏览:

Django教程-Django新闻应用

点击关注 Python架构师
Python架构师

gh_1d7504e4dee1

回复:python,领取Python面试题。分享Python教程,Python架构师教程,Python爬虫,Python编程视频,Python脚本,Pycharm教程,Python微服务架构,Python分布式架构,Pycharm注册码。

收录于合集
#django 31
#Django开源项目 42
#Django教程 41
#python web教程 50
#python教程 138
整理:python架构师
我们可以使用高级的Python框架Django构建服务器端的Web应用程序。在本教程中,我们将学习如何使用Django构建一个新闻应用程序。我们将使用News API来获取所有的头条新闻。您可以访问News API的网站以了解更多信息。
强大而灵活的Django REST框架是用于创建Web API的框架。用户可以使用这个Python脚本创建一些非常酷和令人惊叹的Web应用程序。在本博文中,我们将探讨如何从头开始在Django中构建一个新闻应用程序。您也应该向大家展示这个项目。回到我们的项目中,我们将使用News API来获取新闻。
术语“应用程序编程接口”,有时被称为“API”,在今天经常被使用。API意味着提供一个接口,使得多个程序之间可以共享数据或进行通信。当您使用社交媒体平台如Facebook来交换即时消息,或使用手机天气应用来查看天气时,您就在使用API。
创建一个名为“templates”的文件夹在您的newsapp设置中。

资源分享

点击领取:最全Python资料合集

代码部分:

# 导入所需的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%

版权:如无特殊注明,文章转载自网络,侵权请联系cnmhg168#163.com删除!文件均为网友上传,仅供研究和学习使用,务必24小时内删除。
相关推荐