Pithon Script
Pithon Script
5J5UdOPwYT
Classic token:
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
#!/usr/bin/env python3
import os
import requests
#Path to data
path = "data/feedback"
folder = os.listdir(path)
for file in folder:
Keycount = 0
fb = {}
with open(path + file) as fl:
for line in fl:
value = line.strip()
fb[keys[keycount]] = value
keycount = keycount ++
print(fb)
response = requests.post("http:///feedback")
print(response.request.body)
print(response.status_code)
sales
#!/usr/bin/env python3
import json
import locals
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 content of a 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):
"""When it is Given a Car dictionary, it returns a tidy formated name."""
return "{} {} ({})".format(
car["car_make"], car["car_model"], car["car_year"])
def process_data(data):
locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
max_revenue = {"revenue": 0)
sales ={"total_sales": 0)
best_car = {}
for item in data:
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
summary = [
format_car(max_revenue["car"]),max_revenue["revenue"]),
]
return summary
def car_dict_to_table(car_data):
table_data = [["ID", "Car", "Price", "Total Sales"]]
for item in car_data:
table_data.append9[item["id"], format_car(item["car"]),item["price"],
item["total_sale$"]
return table_data
def main(argv)
data = load_data("/home/student/car_sales.json")
summary = process_data(data)
print(summary)
report('/tmp/cars.pdf', "Cars report", new_summary, car_dict_to_table(data))
msg = email_generate("automation@example.com","<username>@example.com", "Sales
summary for last month", new_summary, "tmp/cars.pdf")
email_send(msg)
if __name__ == "__main__":
main(sys.argv)
new
#!/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."""
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/student-03-e8afec9fe6ff/car_sales.json")
summary = process_data(data)
new_summary = '<br/>'.join(summary)
print (summary)
# TODO: turn this into a PDF report
report('/tmp/cars.pdf', "Cars report", new_summary, car_dict_to_table(data))
# TODO: send the PDF report as an email attachment
msg = email_generate("automation@example.com","student-03-
e8afec9fe6ff@example.com", "Sales summary for last month", new_summary,
"tmp/cars.pdf")
email_send(msg)
if __name__ == "__main__":
main(sys.argv)
indented text
#!/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."""
locale.setlocale(locale.LC_ALL, 'de inlocuit cu ce este available(local -a)')
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/student-03-e8afec9fe6ff/car_sales.json")
summary = process_data(data)
new_summary = '<br/>'.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", "student-03-
e8afec9fe6ff@example.com", "Sales summary for last month", new_summary,
"/tmp/cars.pdf")
email_send(msg)
if __name__ == "__main__":
main(sys.argv)
#################################
#!/usr/bin/env python3
import os
import sys
user = os.getenv('USER')
image_directory = "/home/{}/supplier-data/images/'.format(user)
for image_name in os.listdir(imageimage_directory):
if not image_name.startswith('.') and 'tiff" in image_name:
image_path = image_directory + image_name
path = os.path.splittext(image_path)[0]
im = Image.open(image_path)
new_path = '{}.jpeg'.format(path)
im.convert('RGB'.resize((600, 400)).save(new_path, "JPEG")
#################################
#!/usr/bin/env python3
import requests, os
url = "http://localhost/upload/"
USER = os.getenv('USER')
image_directory = '/home/{}/supplier-data/images/'.format(USER)
files = os.listdir(image_directory)
for image_name in files:
if not image_name.startswith('.') and 'jpeg' in image_name:
image_path = image_directory + image_name
with open(image_path, 'rb') as opened:
r = requests.post(url, files = {'file': opened})
###############################################
#run.py
#!/usr/bin/env python3
import os
import requests
import json
def_data(url,description_dir):
fruit = {}
for item in os.listdir(description_dir):
fruit.clear()
filename = os.path.join(description_dir, item)
with open (filename) as f:
line = f.readlines()
description = ""
for i in range(2,len(line)):
description = description + line[i].strip('\n').replace(u'\
xa0',u'')
fruit["description"]= description
fruit["weight"] = int(line[1].strip('.txt')) + '.jpeg'
print(fruit)
if url! = "":
response = requests.post(url, json = fruit)
print(response.request.url)
print(response.status_code)
return 0
if __name__ == '__main__':
url = 'http://localhost/fruits/'
user = os.getenv('USER')
description_directory =
'/home/{}/supplier-data/descriptions/'.format(user)
catalog_data(url, description_dyrectory)
######################################################
#reports.py
#!/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.build([report_title, empty_line, report_info, empty_line])
###############################################
report-email.py
#!/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):
res = []
wt = []
for item in os.listdir(desc_dir):
filename = os.path.join(desc_dir,item)
with open(filename) as f:
line-f.readlines()
weight = line[1].strip('\n')
name = line[0].strip('\n')
print(name,weight)
res.append('name: ' +name)
wt.append('weight: ' +weight)
print(res)
print(wt)
new_obj = ""
for i in range(len(res)):
if res[i] and input_for == 'pdf':
new_obj == res[i] + '<br /' + '<br /'
return new_obj
if __name__ == "__main__"
user = os.getenv('USER')
decription_directory = '/home/{}/supplier-
data/descriptions/'.format(user)
current_date =
datetime.date.today().strftime("%B %d %Y")
title = 'Proceed Update on ' +
str(current_date)
generate_report('/tmp/processed.pdf',
title, pdf_body('pdf',description_directory))
email_subject = 'Upload completed - Online
Fruit Store'
email_body = 'All fruits are uploaded to
our website successfully. A detailed list is attached to this email.'
msg =
generate_email("automation@example.com", "usernme@example.com".format(user),
email_subject, email_body, "/tmp/processed.pdf")