corona data with python flask get pdf
# Import necessary libraries
from flask import Flask, request, render_template
import requests
from fpdf import FPDF
# Create a Flask app
app = Flask(__name__)
# Define a route to handle the request
@app.route('/generate_pdf', methods=['GET'])
def generate_pdf():
# Fetch corona data from an API (replace with your API endpoint)
corona_data = requests.get('https://api.example.com/corona_data').json()
# Create a PDF object
pdf = FPDF()
pdf.add_page()
# Set font for the PDF
pdf.set_font("Arial", size=12)
# Add title to the PDF
pdf.cell(200, 10, txt="Corona Data Report", ln=True, align='C')
pdf.ln(10)
# Add corona data to the PDF
for country, cases in corona_data.items():
pdf.cell(200, 10, txt=f"{country}: {cases} cases", ln=True)
# Save the PDF file
pdf.output("corona_data_report.pdf")
return "PDF generated successfully!"
if __name__ == '__main__':
app.run(debug=True)
In this Flask application, we create a route /generate_pdf
that handles a GET request to generate a PDF report of corona data. Here are the explanations for each step:
- Import necessary libraries:
- We import the Flask framework to create a web application.
- We import the
request
module to handle HTTP requests. - We import the
render_template
function (although it's not used in this example). - We import the
requests
library to make an HTTP request to fetch corona data. We import the
FPDF
class from thefpdf
library to create a PDF document.Create a Flask app:
We create a Flask application instance called
app
.Define a route to handle the request:
We define a route using the
@app.route
decorator for the endpoint/generate_pdf
, which will handle GET requests.Inside the
generate_pdf
function:We fetch corona data from an example API (you should replace the URL with your own API endpoint) using the
requests.get()
method and parse it as JSON.Create a PDF object:
We create an instance of the
FPDF
class to create a PDF document.Set font for the PDF:
We set the font for the PDF to "Arial" with a font size of 12 points.
Add title to the PDF:
We add a title to the PDF document by using the
pdf.cell()
method. We center-align the title and move to the next line usingln=True
.Add corona data to the PDF:
We iterate through the corona data (assuming it's a dictionary where keys are countries and values are cases) and add each country's data to the PDF using
pdf.cell()
.Save the PDF file:
We save the generated PDF file with the name "corona_data_report.pdf" using the
pdf.output()
method.Run the Flask app:
- We check if the script is being run directly (not imported as a module) and then start the Flask app in debug mode.
When you visit the /generate_pdf
endpoint in your browser, it will trigger the generation of the PDF file containing the corona data.