Skip to content

Instantly share code, notes, and snippets.

@ikari-pl
Created April 28, 2020 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikari-pl/2b8896a5a99b53162f229fa928adf1de to your computer and use it in GitHub Desktop.
Save ikari-pl/2b8896a5a99b53162f229fa928adf1de to your computer and use it in GitHub Desktop.
"""
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