How to Generate Random Cat Facts Using Python

how to generate random cat facts

Introduction

Install modules

To begin we need to install a few modules, to do so run the commands shown below on your terminal.

pip3 install Flask

pip3 install requests

Flask will be our primary web server and requests will be used to make HTTP requests.

File structure

Now let’s create a folder called catfacts which will contain our project files. Inside the folder create a folder called templates and insert a file called index.html.

Import modules

To begin create a file called app.py inside the catfacts folder and import the following modules as shown below.

from flask import Flask, render_template
import requests 

Initialize

Let’s now initialize our application, to do so add the code below.

app = Flask(__name__)

Create view

Now let’s create a view that will generate random cat facts from an API as shown below.

@app.route('/')
def index():
    url = "https://cat-fact.herokuapp.com/facts"
    response = requests.get(url).json()[0]
    text = response['text']
    return render_template("index.html",text=text)

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

Templates

Now let’s create a template to render the generated text. Insert the code below to the file index.html create earlier.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        div {
            text-align: center;
        }
    </style>
    <div>
        <h1>Random Cat fact</h1>
    </div>
    <div>
        <p>{{text}}</p>
    </div>
</body>
</html>

Run

Now let’s run our application, to do so open your terminal and run the command shown below.

python3 app.py

Results

After the command above executes successfully your application should be available at the address [ htpp://127.0.0.1:5000 ]. Here is the application shown below.

There you have it, Thanks for reading. Happy Coding.

Leave a Comment

Your email address will not be published. Required fields are marked *