ゆーじぇいブログ

ゆーじぇいブログ

プログラミングとか色々

[Django]NewsAPIを使ってニュースサイトを作ってみる

f:id:jyouj:20181126215355p:plain

ニュースサイトみたいなのを作りたいと思って調べてみたら、NewsAPI(https://newsapi.org/)っていうのがあったので、これを使って、こんなニュースサイトを作ろうと思いました。

f:id:jyouj:20181126215648p:plain

ソースコードも置いときますので、よければ参照ください。

github.com

NewsAPIを入手する

NewsAPIのサイト(https://newsapi.org/)に行き、指示通りメアド等を入力して発行する。

Resistration Completeという画面にAPIキーが表示されるので、メモしておきましょう。

NewsAPIを設定する

NewsAPIをDjangoで使えるように、パッケージをインストールしておきましょう。

$ pip install newsapi-python

APIgithubとかにあげてはダメなので、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に!