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('').json()

    # Create a PDF object
    pdf = FPDF()

    # 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')

    # 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

    return "PDF generated successfully!"

if __name__ == '__main__':

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:

  1. Import necessary libraries:
  2. We import the Flask framework to create a web application.
  3. We import the request module to handle HTTP requests.
  4. We import the render_template function (although it's not used in this example).
  5. We import the requests library to make an HTTP request to fetch corona data.
  6. We import the FPDF class from the fpdf library to create a PDF document.

  7. Create a Flask app:

  8. We create a Flask application instance called app.

  9. Define a route to handle the request:

  10. We define a route using the @app.route decorator for the endpoint /generate_pdf, which will handle GET requests.

  11. Inside the generate_pdf function:

  12. 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.

  13. Create a PDF object:

  14. We create an instance of the FPDF class to create a PDF document.

  15. Set font for the PDF:

  16. We set the font for the PDF to "Arial" with a font size of 12 points.

  17. Add title to the PDF:

  18. 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 using ln=True.

  19. Add corona data to the PDF:

  20. 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().

  21. Save the PDF file:

  22. We save the generated PDF file with the name "corona_data_report.pdf" using the pdf.output() method.

  23. 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.