News website using Flask and news API - Working with templates : Part 5

Hey guys,
Today we will display data on the webpage from API.

app.py
from flask import Flask, render_template,url_for, request, redirect
import requests as rq

# intialise data of lists.

app = Flask(__name__)

@app.route('/')
def index():
         
    api_key="Your_API_Key"
    url="http://newsapi.org/v2/top-headlines?country=in&apiKey="+api_key
    data=rq.get(url)
    data=data.json()
    articles=data["articles"]

 
    return render_template('index.html',articles=articles)


if __name__=="__main__":
    app.run()

render_template - Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically.
To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:

Flask will look for templates in the templates folder.(as shown in figure) So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
 
Folder Structure:



Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the Jinja template library to render templates.
In your application, you will use templates to render HTML which will display in the user’s browser. In Flask, Jinja is configured to autoescape any data that is rendered in HTML templates. This means that it’s safe to render user input; any characters they’ve entered that could mess with the HTML, such as < and > will be escaped with safe values that look the same in the browser but don’t cause unwanted effects.
Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between {{ and }} is an expression that will be output to the final document. {% and %} denotes a control flow statement like if and for. Unlike Python, blocks are denoted by start and end tags rather than indentation since static text within a block could change indentation.

base.html
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
    <title>News</title>
    {% block head %}
    {% endblock %}
</head>

<body>
    <div class="container py-3 my-3">
        {% block body %}


        {% endblock %}
    </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
    </script>
</body>
<footer class="bg-dark mb-0 p-3">
    <p class="text-center text-white  m-0 p-0"><a href="https://newsapi.org/" class="text-white text-center">newsapi</a>
    </p>
    <p class="text-center text-white m-0 p-0">credits : Mitesh Masurkar</p>
</footer>


</html>

Each page in the application will have the same basic layout around a different body. Instead of writing the entire HTML structure in each template, each template will extend a base template and override specific sections.

index.html
{% extends 'base.html' %}
{% block body %}
<div class="container p-3">
  <h1 class="text-center">News</h1>
  <p class="text-center">Stay Up to Date</p>
</div>

<hr />
<div class="container">
  <div class="row my-3">
    {% for article in articles %}
    <div class=" col-md-4 col-sm-12 col-lg-4">
      <div class="card my-3">
        <a href="{{ article.urlToImage }}">
          <img
            class="card-img-top"
            src="{{ article.urlToImage }}"
            alt="{{ article.urlToImage }}"
        /></a>
        <div class="card-body">
          <h5 class="mt-0">{{ article.title }}</h5>
          <p class="p-0 m-0 " style="font-weight: bold; font-size: 10px;">
            {{article["source"]["name"]}}
          </p>
          <p class="p-0 m-0 text-muted" style="font-size: 10px;">
            {{article.publishedAt[:10] }}
            <span> {{article.publishedAt[11:19] }}</span>
          </p>
          <p class="py-2">
            {{article.description}}
          </p>
        </div>
        <div class="card-footer text-center">
          <a href="{{ article.url }}" class="btn btn-primary text-center"
            >Read Here</a
          >
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>

{% endblock %}

{% extends 'base.html' %} tells Jinja that this template should replace the blocks from the base template. All the rendered content must appear inside {% block %} tags that override blocks from the base template.

articles will return list of articles.
"articles": [
we can access attributes using dot operator.



output:



❤❤Quarantine python group link ❤❤

8805271377 WhatsApp

Follow here ❤

@mr._mephisto_ Instagram 

There will be no restrictions just feel free to learn. 

Share and take one more step to share knowledge with others. 

Believe in yourself 🤟 you are awesome. 

Be safe, Be happy😁
Take care of yourself and your family 
Of course, watch movies and series🤟😉 

And follow the guidelines of the government

Comments

Post a Comment

Popular posts from this blog

News website using Flask and news API - working with API : Part 4

Web Design Challenge

Top programming languages to learn in 2023