In part one of our series we discussed a small (Python) script.
We went through the most obvious code smells and fixed them in the code below.
http_user_service_url = "https://api.coding-on-my-mind.com/users"
http_user_service_username = os.envviron.get("HTTP_USER_SERVICE_USERNAME")
http_user_service_password = os.envviron.get("HTTP_USER_SERVICE_PASSWORD")
age_in_years = 18
userdata_filename = "./clients.csv"
from datetime import datetime, timedelta
import sys
import requests
from requests.auth import HTTPBasicAuth
from configuration import http_user_service_url, http_user_service_username, http_user_service_password,
userdata_filename, age_in_years
import csv
f = open(userdata_filename, 'w')
writer = csv.writer(f)
now = datetime.now()
min_age = now - timedelta(days=age_in_years * 365)
response = requests.get(http_user_service_url, auth=HTTPBasicAuth('u938453', 'Wxc6$78gfsgOi8kr'))
# print(response)
if response.status_code != 200:
print(f"Could not make a successful request to ${url}")
sys.exit(1)
response_dict = response.json()
all_users = response_dict['results']
counter = 0
for user in all_users:
birth_date_str = user['birth_date']
birth_date = datetime.fromisoformat(birth_date_str)
if birth_date < min_age:
if user['country'] == "Spain":
new_user = {
"name": f"{user["title"]} {user["first_name"]} {user["last_name"]}",
"street": user["street"],
"city": f"{user["postal_code"]} {user["city"]}",
"country": user["country"],
}
if counter == 0:
writer.writerow(new_user.keys())
writer.writerow(new_user.values())
counter = counter + 1
else:
print(f"User with id ${user['id']} is not from Spain")
else:
print(f"User with id ${user['id']} is not old enough and will be skipped")
f.close()
We improved the code a little bit in comparison to the code from our first part.