Automating Real World Tasks with Python Week 4 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 is Qwiklab’s Assessment: “Automate Updating catalog Information”

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!


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

Course Link Click here

Qwiklab’s Assessment: “Automate Updating Catalog Information”


					import os, sys
from PIL import Image

user = os.getenv('USER') # To get the username from environment variable
image_directory = '/home/{}/supplier-data/images/'.format(user)
for image_name in os.listdir(image_directory):
    if not image_name.startswith('.') and 'tiff' in image_name:
        image_path = image_directory + image_name
        path = os.path.splitext(image_path)[0]
        im =
        new_path = '{}.jpeg'.format(path)
        im.convert('RGB').resize((600, 400)).save(new_path, "JPEG")

					#!/usr/bin/env python3
import requests, os
# The URL to upload the images
url = "http://localhost/upload/"
# To get the username from environment variable
USER = os.getenv('USER')
# The directory which contains all the images.
image_directory = '/home/{}/supplier-data/images/'.format(USER)
# Listing all the files in images directory
files = os.listdir(image_directory)
# Parsing through all the images
for image_name in files:
    # Accepting files that has jpeg extension and ignoring hidden files
    if not image_name.startswith('.') and 'jpeg' in image_name:
        # creating absolute path for each image
        image_path = image_directory + image_name
        # uploading jpeg files
        with open(image_path, 'rb') as opened:
            r =, files={'file': opened})

					#!/usr/bin/env python3

import os, requests, json

def catalog_data(url,description_dir):
    """This function will return a list of dictionaries with all the details like name, weight, description, image_name.
    It will change the weight to integer format.
    for item in os.listdir(description_dir):
      with open(filename) as f:
        for i in range(2,len(line)):
        if url!="":
, json=fruit)
    return 0
if __name__=='__main__':
    url = 'http://localhost/fruits/'
    user = os.getenv('USER')
    description_directory = '/home/{}/supplier-data/descriptions/'.format(user)

					#!/usr/bin/env python3

from reportlab.platypus import Paragraph, Spacer, Image, SimpleDocTemplate
from reportlab.lib.styles import getSampleStyleSheet

def generate_report(file, title, add_info):
    styles = getSampleStyleSheet()
    report = SimpleDocTemplate(file)
    report_title = Paragraph(title, styles['h1'])
    report_info = Paragraph(add_info, styles['BodyText'])
    empty_line = Spacer(1,20)[report_title, empty_line, report_info, empty_line])

					#!/usr/bin/env python3

import datetime
import os

from run import catalog_data
from reports import generate_report
from emails import generate_email, send_email

def pdf_body(input_for,desc_dir):
    """Generating a summary with two lists, which gives the output name and weight"""
    res = []
    wt = []
    for item in os.listdir(desc_dir):
      with open(filename) as f:
        res.append('name: ' +name)
        wt.append('weight: ' +weight)
    new_obj = ""  # initializing the object
    # Calling values from two lists one by one.
    for i in range(len(res)):
        if res[i] and input_for == 'pdf':
            new_obj += res[i] + '<br />' + wt[i] + '<br />' + '<br />'
    return new_obj

if __name__ == "__main__":
    user = os.getenv('USER')
    description_directory = '/home/{}/supplier-data/descriptions/'.format(user)  # The directory which contains all the files with data in it.
    current_date ="%B %d, %Y")  # Creating data in format "May 5, 2020"
    title = 'Processed Update on ' + str(current_date)  # Title for the PDF file with the created date
    generate_report('/tmp/processed.pdf', title, pdf_body('pdf',description_directory))  # calling the report function from custom module
    email_subject = 'Upload Completed - Online Fruit Store'  # subject line give in assignment for email
    email_body = 'All fruits are uploaded to our website successfully. A detailed list is attached to this email.'  # body line give in assignment for email
    msg = generate_email("", "<username>".format(user),
                         email_subject, email_body, "/tmp/processed.pdf")  # structuring email and attaching the file. Then sending the email, using the cus$

					#!/usr/bin/env python3

import email
import mimetypes
import smtplib
import os

def generate_email(sender, recipient, subject, body, attachment_path):
    """Creates an email with an attachement."""
    # Basic Email formatting
    message = email.message.EmailMessage()
    message["From"] = sender
    message["To"] = recipient
    message["Subject"] = subject

    # Making attachment_path optional, if the attachment variable is empty string, no email will be sent.
    if not attachment_path == "":
        # Process the attachment and add it to the email
        attachment_filename = os.path.basename(attachment_path)
        mime_type, _ = mimetypes.guess_type(attachment_path)
        mime_type, mime_subtype = mime_type.split('/', 1)

        with open(attachment_path, 'rb') as ap:
            message.add_attachment(, maintype=mime_type, subtype=mime_subtype,

    return message

def send_email(message):
    """Sends the message to the configured SMTP server."""
    mail_server = smtplib.SMTP('localhost')

					#! /usr/bin/env python3

import os
import shutil
import psutil
import socket
from emails import generate_error_report, send_email

def check_cpu_usage():
    """Verifies that there's enough unused CPU"""
    usage = psutil.cpu_percent(1)
    return usage > 80

def check_disk_usage(disk):
    """Verifies that there's enough free space on disk"""
    du = shutil.disk_usage(disk)
    free = / * 100
    return free > 20

def check_available_memory():
    """available memory in linux-instance, in byte"""
    available_memory = psutil.virtual_memory().available/(1024*1024)
    return available_memory > 500

def check_localhost():
    """check localhost is correctly configured on"""
    localhost = socket.gethostbyname('localhost')
    return localhost == ''

if check_cpu_usage():
    error_message = "CPU usage is over 80%"
elif not check_disk_usage('/'):
    error_message = "Available disk space is less than 20%"
elif not check_available_memory():
    error_message = "Available memory is less than 500MB"
elif not check_localhost():
    error_message = "localhost cannot be resolved to"

# send email if any error reported
if __name__ == "__main__":
        sender = ""
        receiver = "{}".format(os.environ.get('USER'))
        subject = "Error - {}".format(error_message)
        body = "Please check your system and resolve the issue as soon as possible"
        message = generate_error_report(sender, receiver, subject, body)
    except NameError:

2 thoughts on “Automating Real World Tasks with Python Week 4 Solution

  1. Hi,
    Can you send me the code for:

    Automating Real-World Tasks with Python WEEK 3, and WEEK 4 Qwiklabs Assessment Coursera

    Best Regards,

  2. Hi, I see you’re importing “generate_error_report” from in health_check, but there is no function like that in the file. Can you advise?

Leave a Reply

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