フラスコを使用したニュースアプリケーションの作成


last part , 私たちはフラスコを使用して簡単なハローワールドアプリケーションを見ていた.この部分では、同じコードベースを使用してニュースアプリケーションを作成します.我々は、アプリケーションを魅力的に見えるようにテンプレートや静的なファイルを使用します.ニュースのために、我々は使用されますNews API . では、ダイビングをしましょう!


テンプレート
テンプレートは、アプリケーションでHTMLページを提供するために使用するHTMLファイルです.我々がすでに議論したようにprevious blog , これらのファイルはtemplates ディレクトリ内core パッケージ.では、作成しましょうtemplates ディレクトリ内core パッケージ.また、作成しましょうindex.html ファイルの内部templates ディレクトリ.
$ mkdir core/templates
$ touch core/templates/index.html
今、私たちは私たちのアプリケーションのためのHTMLファイルを使用します、なぜ我々はこれのブートストラップを使用しないでください?Bootstrap 迅速に設計し、応答性モバイル最初のサイトをカスタマイズできます.それを言って、その上に頭をstarter template ブートストラップとコピーによって与えられ、それをindex.html ファイル
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Bootstrap CSS -->
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />

    <title>Hello, {{ user.name }}!</title>
  </head>
  <body>
    <h1>Hello, {{ user.name }}!</h1>

    <!-- Bootstrap Bundle with Popper -->
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

これはbootstrapによって提供される簡単な起動テンプレートです.これは、ブートストラップで指定されたCSSとJavaScriptが含まれます.これを開くと、メッセージが表示されます.Hello Worldメッセージの代わりに、我々はそれをカスタマイズさせたいです.だから、我々は使用しているHello, {{ user.name }} Jinja 2テンプレートエンジンを使用します.さて、フラスコを使ってこのページをどのように提供するかを見てみましょう.
from core import app
from flask import render_template # Add this line

@app.route('/')
def say_hello():
    user = {"name": "Ashutosh"}
    return render_template("index.html", user=user) # Modify this line

FlaskアプリケーションからHTMLページを作成するには、render_template() フラスコ自体によって提供される方法.このメソッドはテンプレートファイル名とテンプレート引数の変数リストを受け取り、同じテンプレートを返しますが、すべてのプレースホルダを実際の値に置き換えます.The render_template() メソッドはJinja2 Flaskフレームワークにバンドルされているテンプレートエンジン.Jinja 2代用品{{ ... }} 対応する値を持つブロックrender_template() コール.
では、サーバを起動して出力を見てみましょう.

あなたは、我々が我々が通ったどんな名前でも見ましたuser 辞書、出力に同じ名前を持っています.このようにして動作します.

静的ファイル
さて、HTMLテンプレートの静的なファイルをどのように提供するかを見てみましょう.静的なファイルには、CSS、JavaScript、画像、フォントなどがあります.すでにCSSとJavaScriptがブートストラップで提供されているので、イメージを提供しましょう.そのためにstatic ディレクトリ内core パッケージの中でimages フォルダ.
$ mkdir core/static
$ mkdir core/static/images
任意の画像をフォルダ内に置くことができます.Aを使っていますdemo.jpg 例えば、イメージ.これにより、HTMLテンプレートに静的ファイルを使用できます.
<img src="{{ url_for('static', filename='images/demo.jpg') }}" alt="">
フラスコは、Aを提供しますurl_for 動的にURLを生成する関数.私たちはimages/demo.jpg ファイルの内部static フォルダ.この行をhelloメッセージの下に置きましょう.出力は以下のようになります.


ニュースAPI
今、私たちは、アプリケーションの主要な部分にジャンプしましょう-どのようにニュースの見出しを取得します.この目的のために、我々は使用するつもりですNews API . サインアップ無料アカウントとニュースAPIからAPIキーを取得します.APIキーを取得すると、.env トップレベルのディレクトリにファイルを追加し、APIキーを保存します.
NEWS_API_KEY=YOUR-API-KEY-HERE
環境変数についてもっと学ぶことができますhere . 環境変数を使用するには、外部ライブラリpython-decouple . 以下のようにインストールできます:
$ pip install python-decouple
インストール済みのutils.py ファイルの内部core パッケージ.このファイルの中で、最新ニュースの見出しを取得します.ニュースAPIにはPythonライブラリがありますnewsapi-python . しかし、それを使用する代わりに、我々はrequests 図書館.以下のようにインストールする必要があります.
$ pip install requests
Pythonを使ってAPIを使う方法を学ぶことができますthis blog .
さて、我々はすべての準備ができている、私たちはutils.py ファイル.開けるutils.py ファイルを追加し、次のコードを追加します
import requests
from decouple import config

NEWS_API_KEY = config('NEWS_API_KEY')
COUNTRY = 'in'

def get_latest_news():
    news_data = requests.get(f'https://newsapi.org/v2/top-headlines?country={COUNTRY}&apiKey={NEWS_API_KEY}').json()
    return news_data['articles']

上記のスクリプトでは、2つのインポートがあります.requests ニュースを得るconfig 環境変数の値を.env ファイル.次に、APIキーの値を変数NEWS_API_KEY . また、設定しているCOUNTRY つまりインドに.あなたは、ニュースAPIドキュメンテーションでいろいろな国の国コードを見つけることができます.私たちがしている次のことはget_latest_news() 関数.その中で、我々はニュースAPIによって提供されるURLにGET要求をしていますhere 国とAPIキーパラメータで.我々は応答をJSONに変換している.次のようになります.
{
  "status": "ok",
  "totalResults": 38,
  "articles": [
    {
      "source": {
        "id": null,
        "name": "Sportskeeda"
      },
      "author": "Aniket Thakkar",
      "title": "Latest Free Fire redeem code to get Weapon loot crate today (14 October 2021) - Sportskeeda",
      "description": "Gun crates are one of the ways that players in Free Fire can obtain impressive and appealing gun skins.",
      "url": "https://www.sportskeeda.com/free-fire/latest-free-fire-redeem-code-get-weapon-loot-crate-today-14-october-2021",
      "urlToImage": "https://staticg.sportskeeda.com/editor/2021/10/d0b83-16341799119781-1920.jpg",
      "publishedAt": "2021-10-14T03:51:50Z",
      "content": null
    },
    {
      "source": {
        "id": null,
        "name": "NDTV News"
      },
      "author": null,
      "title": "BSF Gets Increased Powers In 3 Border States: What It Means - NDTV",
      "description": "Border Security Force (BSF) officers will now have the power toarrest, search, and of seizure to the extent of 50 km inside three newstates sharing international boundaries with Pakistan and Bangladesh.",
      "url": "https://www.ndtv.com/india-news/bsf-gets-increased-powers-in-3-border-states-what-it-means-2574644",
      "urlToImage": "https://c.ndtvimg.com/2021-08/eglno7qk_-bsf-recruitment-2021_625x300_10_August_21.jpg",
      "publishedAt": "2021-10-14T03:44:00Z",
      "content": "This move is quickly snowballing into a debate on state autonomy. New Delhi: Border Security Force (BSF) officers will now have the power to arrest, search, and of seizure to the extent of 50 km ins… [+4143 chars]"
    },
    {
      "source": {
        "id": "the-times-of-india",
        "name": "The Times of India"
      },
      "author": "TIMESOFINDIA.COM",
      "title": "5 health conditions that can make your joints hurt - Times of India",
      "description": "Joint pain caused by these everyday issues generally goes away on its own when you stretch yourself a little and flex your muscles.",
      "url": "https://timesofindia.indiatimes.com/life-style/health-fitness/health-news/5-health-conditions-that-can-make-your-joints-hurt/photostory/86994969.cms",
      "urlToImage": "https://static.toiimg.com/photo/86995017.cms",
      "publishedAt": "2021-10-14T03:30:00Z",
      "content": "Depression is a mental health condition, but the symptoms may manifest even on your physical health. Unexpected aches and pain in the joints that you may experience when suffering from chronic depres… [+373 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "The Indian Express"
      },
      "author": "Devendra Pandey",
      "title": "Rahul Dravid likely to be interim coach for New Zealand series - The Indian Express",
      "description": "It’s learnt that a few Australian coaches expressed interest in the job, but the BCCI isn’t keen as they are focussing on an Indian for the role, before they look elsewhere.",
      "url": "https://indianexpress.com/article/sports/cricket/rahul-dravid-likely-to-be-interim-coach-for-new-zealand-series-7570990/",
      "urlToImage": "https://images.indianexpress.com/2021/05/rahul-dravid.jpg",
      "publishedAt": "2021-10-14T03:26:09Z",
      "content": "Rahul Dravid is likely to be approached by the Indian cricket board to be the interim coach for Indias home series against New Zealand. Head coach Ravi Shastri and the core of the support staff will … [+1972 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "CNBCTV18"
      },
      "author": null,
      "title": "Thursday's top brokerage calls: Infosys, Wipro and more - CNBCTV18",
      "description": "Goldman Sachs has maintained its 'sell' rating on Mindtree largely due to expensive valuations, while UBS expects a muted reaction from Wipro's stock. Here are the top brokerage calls for the day:",
      "url": "https://www.cnbctv18.com/market/stocks/thursdays-top-brokerage-calls-infosys-wipro-and-more-11101072.htm",
      "urlToImage": "https://images.cnbctv18.com/wp-content/uploads/2019/03/buy-sell.jpg",
      "publishedAt": "2021-10-14T03:26:03Z",
      "content": "MiniGoldman Sachs has maintained its 'sell' rating on Mindtree largely due to expensive valuations, while UBS expects a muted reaction from Wipro's stock. Here are the top brokerage calls for the day:"
    }
  ]
}

ニュースがリストに含まれているのでarticles , 帰りますnews_data['articles'] 関数から.現在、我々は我々のルートでこの機能を使用する準備ができています.

ニュースページ
ブートストラップのみを使用してニュースページをデザインします.だから、作成するnews.html ファイルの内部templates ディレクトリと次のコードを追加します
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Bootstrap CSS -->
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />

    <title>Latest News Headlines</title>
  </head>
  <body>
    <h1 class="text-center mt-4 mb-5">Latest News Headlines</h1>
    <div class="row mt-5">
      <div class="col-md-2"></div>
      <div class="col-md-8">
        <div class="row">
          {% for news in news_articles %}
          <div class="col-md-4 mb-5">
            <div class="card" style="width: 18rem">
              <img src="{{ news.urlToImage }}" class="card-img-top" alt="..." />
              <div class="card-body">
                <h5 class="card-title">{{ news.title }}</h5>
                <p class="card-text">{{ news.description }}</p>
                <a href="{{ news.url }}" class="btn btn-primary">Read More</a>
              </div>
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
      <div class="col-md-2"></div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

コードは、あなたに現在身近に見えます.テンプレートの本文では、見出しを追加しました.以下は使用しているJinja2 for loop を繰り返すnews_articles リストは、我々のルートによって通りました.使用済みBootstrap cards 各ニュース.これは、完全なニュースを読むには、画像、ニュースタイトル、その説明とボタンが含まれます.上記のサンプル応答を見た場合、あなたは見つけるでしょうtitle , description , URL and urlToImage を返します.

ニュースページのルートを作成する
さて、オープンroutes.py ファイルを作成し、ルートを作成する"/news" ニュースページ.
from core import app
from flask import render_template
from .utils import get_latest_news # Add this line

@app.route('/')
def say_hello():
    user = {"name": "Ashutosh"}
    return render_template("index.html", user=user)

# Add this part
@app.route('/news')
def news_headlines():
    news_articles = get_latest_news()
    return render_template("news.html", news_articles=news_articles)

上記のスクリプトではget_latest_news() 機能からutils.py ファイル.次に、ビュー関数を作成しましたnews_headlines() URLマップ"/news" 使用@app.route デコレータ.機能の中で、我々はデータを得ているget_latest_news() 関数はnews_articles リスト以外の変数.我々は、それから我々を与えましたnews.html ファイルをnews_articles リスト.
サーバを実行し、出力を見る準備ができました.

それは驚くべきではありませんか?我々はちょうどフラスコを使用して最初のニュースアプリケーションを作成しました.

結論
このブログでは、我々はニュースアプリケーションを作成している.通り抜けるNews API Documentation いくつかのAPIのエンドポイントを探索します.カスタムCSSを使用することでページをより魅力的に見えます.あなたがチュートリアルが好き願っています.ここでアプリケーションコード全体を見つけることができます.https://github.com/ashutoshkrris/Flask-News-Application