[Django]NewsAPIを使ってニュースサイトを作ってみる
ニュースサイトみたいなのを作りたいと思って調べてみたら、NewsAPI(https://newsapi.org/)っていうのがあったので、これを使って、こんなニュースサイトを作ろうと思いました。
ソースコードも置いときますので、よければ参照ください。
NewsAPIを入手する
NewsAPIのサイト(https://newsapi.org/)に行き、指示通りメアド等を入力して発行する。
Resistration Completeという画面にAPIキーが表示されるので、メモしておきましょう。
NewsAPIを設定する
NewsAPIをDjangoで使えるように、パッケージをインストールしておきましょう。
$ pip install newsapi-python
APIはgithubとかにあげてはダメなので、newsapi.pyを作って、.gitignoreに追加しておきましょう。
そして、先ほどメモしておいたAPIキーをnewsapi.pyに書いときましょう。
NEWS_API = "********"
そして、settings.pyにこれらを付け加えといてください。
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newsapi', 'news', ] from . import newsapi NEWSAPI = newsapi.NEWS_API
これで、Djangoアプリ内でNewsAPIが使えるようになりました。
ニュースサイトを実装しよう
settings.pyと同じディレクトリのurls.pyに記述する。
path('', include('news.urls')),
そして、newsアプリ下にurls.pyを作ります。
urlpatterns = [ path('', views.IndexView.as_view(), name="index"), ]
それでは、views.pyを作って行きましょう。
from django.shortcuts import render from django.views import generic from django.conf import settings from newsapi import NewsApiClient # Create your views here. class IndexView(generic.TemplateView): template_name = "news/index.html" def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) newsapi = NewsApiClient(api_key=settings.NEWSAPI) context['top_headlines'] = newsapi.get_top_headlines(country='jp') # print(context['top_headlines']) return context
たったこれだけですね。print(context['top_headlines'])を実行してどんな値が使えるか確認しておきましょう。
それでは、テンプレートを作っていきます。CSSにはBulmaを使っています。
まずは、base.htmlを記述していきましょう。
{% load static %} <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>SampleNews</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script> <style type="text/css"> a { text-decoration:none; } a:link { color : #000000; } a:visited { color : #000000; } </style> </head> <body> <nav class="navbar is-fixed-top is-light" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <h3 class="title is-3"><a class="navbar-item" href="#">SampleNews</a></h3> </div> </nav> <section class="section"> {% block body %}{% endblock %} </section> <style> body { padding-top: 30px; } </style> </body> </html>
news/index.htmlを作成して完成です!
{% extends 'base.html' %} {% block body %} <section class="hero is-dark"> <div class="hero-body"> <div class="container"> <center><h1 class="title">最新のニュース</h1></center> </div> </div> </section> <div> {% for content in top_headlines.articles %} <div class="card"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="{{ content.urlToImage }}" alt="Placeholder image"> </figure> </div> <div class="card-content"> <div class="media-content"> <p class="title is-4">{{ content.title }}</p> <p class="subtitle is-6">{{ content.author }}</p> </div> </div> <div class="content"> {{ content.description }} <br> <time>{{ content.publishedAt }}</time> </div> </div> {% endfor %} </div> </div> {% endblock %}
NewsAPIを使うと簡単にニュース風のサイトが作れますね!
何かあれば、じぇい👨💻 (@jyouj__) | Twitterに!
【店内全品5倍】Python Django超入門/掌田津耶乃【3000円以上送料無料】
- ジャンル: 本・雑誌・コミック > PC・システム開発 > プログラミング > その他
- ショップ: bookfan 1号店 楽天市場店
- 価格: 3,240円