Get news from three major mobile companies using Django and the News API

Introduction

I am new to programming, so I hope you will read this article with warm eyes.

environment

Windows10 Python 3.7.6 newsapi-python 0.2.6 Django 3.0.6 DateTime 4.3

The name of the directory at the time of creation is as follows.

sample_news
├─news
├─sample_news
├─static
└─manage.py

Introducing News API

Go to News API Site and enter your email address to get the API key, and make a note of the API key. Then use pip to install the NewsAPI library.

pip install newsapi-python

Add the following code to setting.py in sample_news to use the News API. For api_key, enter the key you wrote down.

setting.py


from newsapi import NewsApiClient

newsapi=NewsApiClient(api_key='xxxxxxxxxxxxxxxxxxxxxx')

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'news.apps.NewsConfig',
    'newsapi',
]

You can now use the News API.

Creating a news app

Routing settings

Add the following code to urls.py in sample_news to configure the routing.

sample_news/urls.py


from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('news.urls')),
]

Next, I created urls.py in news and entered the following code.

news/urls.py


from django.urls import path
from.import views

app_name = 'news'
urlpatterns = [
    path('', views.IndexView.as_view(), name="index"),
    path('docomo/',views.DocomoView.as_view(),name="docomo"),
    path('au/',views.AuView.as_view(),name="au"),
    path('softbank/',views.SoftbankView.as_view(),name="softbank")
]

Get news with News API

There are two ways to get the top news in the News API and to get the news for a certain period in the past.

When I got the top news, nothing was displayed if there was no news, so I adopted the method of getting the news for a certain period of time. The News API allows you to get news up to 30 days in advance if you don't charge.

This time, I specified the keyword, period, display order, and number of news. There are also title keywords, sources, domains, languages (Japanese is not allowed), etc.

news/views.py


from django.views import generic
from newsapi import NewsApiClient
from datetime import datetime, date, timedelta

class IndexView(generic.TemplateView):
    template_name = "index.html"

class DocomoView(generic.TemplateView):
    template_name = "docomo.html"

    def get_context_data(self, **kwargs):
        context=super().get_context_data(**kwargs)
        today = date.today()
        monthago = today-timedelta(days=30)
        newsapi = NewsApiClient(api_key='e56b4ed3346745e3800bc521d085e04b')
        context['all_article']=newsapi.get_everything(q='DoCoMo',
                                                      from_param=monthago,
                                                      to=today,
                                                      sort_by='publishedAt',
                                                      page_size=40)
        return context

class AuView(generic.TemplateView):
    template_name = "au.html"

    def get_context_data(self, **kwargs):
        context=super().get_context_data(**kwargs)
        today = date.today()
        monthago = today-timedelta(days=30)
        newsapi = NewsApiClient(api_key='e56b4ed3346745e3800bc521d085e04b')
        context['all_article']=newsapi.get_everything(q='KDDI',
                                                      from_param=monthago,
                                                      to=today,
                                                      sort_by='publishedAt',
                                                      page_size=40)
        return context

class SoftbankView(generic.TemplateView):
    template_name = "softbank.html"

    def get_context_data(self, **kwargs):
        context=super().get_context_data(**kwargs)
        today = date.today()
        monthago = today-timedelta(days=30)
        newsapi = NewsApiClient(api_key='e56b4ed3346745e3800bc521d085e04b')
        context['all_article']=newsapi.get_everything(q='Softbank',
                                                      from_param=monthago,
                                                      to=today,
                                                      sort_by='publishedAt',
                                                      page_size=40)
        return context

Now that the program to get the news is complete, all you have to do is coat it.

Display the acquired news

This time, 4 of the top page (index.html), the page that displays docomo news (docomo.html), the page that displays au news (au.html), and the page that displays Softbank news (softbank.html). I created one page and five html files of the part common to each page (base.html).

templates
├─au.html
├─base.html
├─docomo.html
├─index.html
└─softbank.html

The pages that display doCoMo news are as follows.

This time, the title, url, and news image are acquired and displayed.

docomo.html


{% extends 'base.html' %}
{% block title %}Sample_News | SOFTBANK{% endblock %}
{% block contents %}
<div class="grid">
{% for context in all_article.articles %}
<div class="news">
    <div class="news-wrapper">
        <img class="news-img" src="{{ context.urlToImage }}" alt="">
        <a class="news-title" href="{{ context.url }}">{{ context.title }}</a>
    </div>
</div>
{% endfor %}
</div>
{% endblock %}

Like this, I also write au and Softbank html files.

Finally, coding with CSS is completed.

top page newstop.PNG

DoCoMo news page docomo.PNG

Summary

This is the first web app I made after studying django, so I made it using a lot of reference books. After studying, I felt that I could deepen my understanding by making my own web application for revenge.

I did the search words for docomo for docomo, au for au, and Softbank for softbank, but docomo output only docomo news, but au outputs overseas news and Softbank outputs baseball news. Since it was done, I would like to improve it.

Also, since this is my first time writing an article, I would appreciate it if you could let me know if there is something you cannot reach.

reference

-Move and learn! Introduction to Python Django Development

Recommended Posts

Get news from three major mobile companies using Django and the News API
How to get followers and followers from python using the Mastodon API
Get the weather using the API and let the Raspberry Pi speak!
Get the address from latitude and longitude
Get only the text from the Django form.
Get all songs of Arashi's song information using Spotify API and verify the index
Get the title of yahoo news and analyze sentiment
[Python] Get the text of the law from the e-GOV Law API
Send and receive Gmail via the Gmail API using Python
Get comments and subscribers with the YouTube Data API
[Django 2.2] Sort and get the value of the relation destination
Get files from Linux using paramiko and scp [Python]
A little bit from Python using the Jenkins API
DJango Note: From the beginning (simplification and splitting of URLConf)
Get your heart rate from the fitbit API in Python!
Get data using Ministry of Internal Affairs and Communications API
Predict gender from name using Gender API and Pykakasi in Python
Get product name and lowest price using Amazon Product Advertising API
I tried to get various information from the codeforces API
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
Try using the Twitter API
Try using the Twitter API
Try using the PeeringDB 2.0 API
Flow of getting the result of asynchronous processing using Django and Celery
[Python] Get the update date of a news article from HTML
DJango memo: From the beginning (using the management screen) my addictive point
Create custom Django commands and run them from the command line
Get the title and delivery date of Yahoo! News in Python