Automating Real World Tasks with Python Week3 Solution

In the final course, we’ll tie together the concepts that you’ve learned up until now. You’ll tackle real-world scenarios in Qwiklab’s that will challenge you to use multiple skills at once. This assignment consist of Qwiklab’s Assessment: “Automatically Generate a PDF and Send it by Email”.

First, we’ll take a closer look at how to use external Python modules to extend your code’s capabilities, and spend some time learning how to use documentation to learn a new module. For example, we’ll use the Python Image Library (PIL) to create and modify images.

We’ll show you some simple examples of how to perform common tasks in the course material, but it will be up to you to explore the module documentation to figure out how to solve specific problems. Next, we’ll show you how to communicate with the world outside of your code! You’ll use data serialization to turn in-memory objects into messages that can be sent to other programs.

Your program will send messages across the network to Application Programming Interfaces (APIs) offered by other programs. For those times when your code needs to talk to a person instead of a program, you’ll also learn to send email messages. At the end of this course, you’ll be able to take a description of a problem and use your skills to create a solution — just like you would on the job. In your final capstone project, you’ll be given a description of what your customer needs, and it will be up to you to create a program to do it!

~~SKILLS YOU WILL GAIN~~

  • Serialization
  • Building a Solution
  • Creating and Translating Media Files
  • Interacting with Web Services

Course Link Click here

Qwiklab’s Assessment: “Automatically Generate a PDF and Send it by Email

Code:-

Execute the below command to avoid ASCII error:
export LC_ALL=”C.UTF-8″

If you encounter any error just replace the, locale.setlocale(locale.LC_ALL, ‘en_US.UTF8’) with, locale.setlocale(locale.LC_ALL, ‘C.UTF-8’)


Cars.py
				
					#!/usr/bin/env python3
import json
import locale
import sys
from reports import generate as report
from emails import generate as email_generate
from emails import send as email_send

def load_data(filename):
    """Loads the contents of filename as a JSON file."""
    with open(filename) as json_file:
        new_data = json.load(json_file)
        data = sorted(new_data, key=lambda i: i['total_sales'])
    return data

def format_car(car):
    """Given a car dictionary, returns a nicely formatted name."""
    return "{} {} ({})".format(
        car["car_make"], car["car_model"], car["car_year"])

def process_data(data):
    """Analyzes the data, looking for maximums.

  Returns a list of lines that summarize the information.
  """
    locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
    max_revenue = {"revenue": 0}
    sales = {"total_sales": 0}
    best_car = {}
    for item in data:
        # Calculate the revenue generated by this model (price * total_sales)
        # We need to convert the price from "$1234.56" to 1234.56
        item_price = locale.atof(item["price"].strip("$"))
        item_revenue = item["total_sales"] * item_price
        if item_revenue > max_revenue["revenue"]:
            item["revenue"] = item_revenue
            max_revenue = item
        # TODO: also handle max sales
        if item["total_sales"] > sales["total_sales"]:
            sales = item
        # TODO: also handle most popular car_year
        if not item["car"]["car_year"] in best_car.keys():
            best_car[item["car"]["car_year"]] = item["total_sales"]
        else:
            best_car[item["car"]["car_year"]] += item["total_sales"]

        all_values = best_car.values()
        max_value = max(all_values)
        max_key = max(best_car, key=best_car.get)

    summary = [
        "The {} generated the most revenue: ${}".format(
            format_car(max_revenue["car"]), max_revenue["revenue"]),
        "The {} had the most sales: {}".format(sales["car"]["car_model"], sales["total_sales"]),
        "The most popular year was {} with {} sales.".format(max_key, max_value),
    ]

    return summary

def cars_dict_to_table(car_data):
    """Turns the data in car_data into a list of lists."""
    table_data = [["ID", "Car", "Price", "Total Sales"]]
    for item in car_data:
        table_data.append([item["id"], format_car(item["car"]), item["price"], item["total_sales"]])
    return table_data

def main(argv):
    """Process the JSON data and generate a full report out of it."""
    data = load_data("/home//car_sales.json")
    summary = process_data(data)
    new_summary = ''.join(summary)
    print(summary)
    # TODO: turn this into a PDF report
    report('/tmp/cars.pdf', "Cars report", new_summary, cars_dict_to_table(data))
    # TODO: send the PDF report as an email attachment
    msg = email_generate("automation@example.com", "@example.com",
                         "Sales summary for last month", new_summary, "/tmp/cars.pdf")
    email_send(msg)

if __name__ == "__main__":
    main(sys.argv)
				
			

Leave a Reply

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