Created
April 28, 2020 09:41
-
-
Save ikari-pl/2b8896a5a99b53162f229fa928adf1de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Retrieve user data from https://jsonplaceholder.typicode.com/users | |
Find users matching usernames given on command line, and print their | |
full name and email address. | |
""" | |
try: | |
from urllib.request import urlopen | |
except: | |
from urllib2 import urlopen | |
import sys | |
from pprint import pprint | |
url = "https://jsonplaceholder.typicode.com/users" | |
search_key = "username" | |
class User: | |
name = "" | |
email = "" | |
def __init__(self, user_name, user_email): | |
self.name = user_name | |
self.email = user_email | |
def __str__(self): | |
return "{0} <{1}>".format(self.name, self.email) | |
class UserList: | |
def __init__(self, users=[]): | |
self.users = users | |
def append(self, user): | |
self.users.append(user) | |
def __str__(self): | |
return "\n".join(str(u) for u in self.users) | |
def find_users(query): | |
found = UserList() | |
for entry in users: | |
if query in entry[search_key]: | |
user = User(entry["name"], entry["email"]) | |
found.append(user) | |
return found | |
response = urlopen(url) | |
data = response.read() | |
users = eval(data) | |
for query in sys.argv[1:]: | |
print("Search results for {0}:".format(query)) | |
found = find_users(query) | |
print(found) | |
print("") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment