The Requests Client Code

This code in is requests/client.py which you can copy from this directory:

cd ~/cs304/
cp -r ~cs304flask/pub/downloads/requests/ requests/

Here's the code. It's pretty short; fewer than 100 lines long. There are some helper functions, just to make the examples more succinct.

import requests

port = 1942

# get the port to use
port = input(f'Enter port (default {port}) ') or port

prefix = f'http://cs.wellesley.edu:{port}'

def check_response_for_error(resp):
    '''Raises an exception if there was an error, otherwise returns the JSON data.'''
    if resp.status_code != 200:
        raise Exception(resp.status_code)
    else:
        val = resp.json()
        if val['error']:
            raise Exception(val['error'])
        else:
            return val

def print_people(dict_list, head=3, tail=3):
    '''prints part of a list of people, represented as dictionaries. 
       Prints the first 'head' elements and then last 'tail' elements.'''
    n = len(dict_list)
    print(f'\nA list of {n} people:')
    for person in dict_list[0:head]:
        nm = person['nm']
        name = person['name']
        bday = person['birthdate']
        print(f'{name} ({nm}) was born on {bday}')
    print('...')
    for person in dict_list[-tail:]:
        nm = person['nm']
        name = person['name']
        bday = person['birthdate']
        print(f'{name} ({nm}) was born on {bday}')

# first example, fetch all people in the database
resp = requests.get(prefix+'/people/')
val = check_response_for_error(resp)
print_people(val['data'])

# second example, fetch all people born in March
resp = requests.get(prefix+'/people-born-in-month/3')
val = check_response_for_error(resp)
print_people(val['data'])

# third example, POST w/o auth
payload = {'nm': 456, 'name': 'Holly Hunter'}
resp = requests.post(prefix+'/people-noauth/', data=payload)
if resp.status_code != 200:
    raise Exception(resp.status_code)
# The POST might fail if the server requires authentication, so let's
# carefully look at the error in the return value
val = resp.json()
if val['error']:
    print('\n***## ERROR in response to POST of Holly Hunter', val['error'])
else:
    print('\n***** response to POST of Holly Hunter', val['data'])

# See that it worked, by fetching all the people:
resp = requests.get(prefix+'/people/')
val = check_response_for_error(resp)
print_people(val['data'])

# default credentials
auth_username = 'me'
auth_password = 'secret'

# get the credentials
print('\n******** Enter Credentials *****')
auth_username = input(f'username: (default: {auth_username}) ') or auth_username
auth_password = input(f'password: (default: {auth_password}) ') or auth_password

# fourth example, LOGIN and then POST w/ auth
credentials = {'username': 'me', 'password': 'secret'}
login_resp = requests.post(prefix+'/login/', credentials)
login_val = check_response_for_error(login_resp)
print('\n***** response to LOGIN', login_val)

session = login_resp.cookies

payload = {'nm': 456, 'name': 'Holly Hunter', 'birthdate': '1958-03-20'}
resp = requests.post(prefix+'/people-auth/', cookies=session, data=payload)
val = check_response_for_error(resp)
print('\n***** response to second POST of Holly Hunter', val)

# Is she there?
resp = requests.get(prefix+'/people-born-in-month/3')
val = check_response_for_error(resp)
print_people(val['data'])