示例#1
0
 def test_date_fields_return_dates_or_none(self):
     for i in range(1,46):
         p = President(i)
         self.assertIsInstance(p.birth_date, date, "birth_date is not datetime.date object")
         self.assertIsInstance(p.death_date, (date, type(None)), "death_date is not datetime.date object or None")
         self.assertIsInstance(p.term_start_date, date, "term_start is not datetime.date object")
         self.assertIsInstance(p.term_end_date, (date, type(None)), "term_end is not datetime.date object or None")
示例#2
0
def handle_client(client):

    while True:
        raw_request = client.recv(1024)

        if not raw_request:
            break

        logging.info("Client request: {0}".format(raw_request))

        (num, field) = raw_request.split()

        p = President(int(num))

        if (field == b'FNAME'): response = p.first_name.encode()
        if (field == b'LNAME'): response = p.last_name.encode()
        if (field == b'BDATE'): response = p.birth_date.encode()
        if (field == b'DDATE'): response = p.death_date.encode()
        if (field == b'TSDATE'): response = p.term_start.encode()
        if (field == b'TEDATE'): response = p.term_end.encode()
        if (field == b'PARTY'): response = p.party.encode()
        if (field == b'BSTATE'): response = p.birth_state.encode()
        if (field == b'BPLACE'): response = p.birth_place.encode()

        client.send(response + b'\n')

    client.close()

    return
def president_by_term(termnum):
    """Retrieve president information for a specified term number"""
    term = int(termnum)
    if 0 < term < 45:
        p = President(term)
        return render_template('president_detail.html', presidents=[p])
    else:
        return '<h2>Sorry,  {} is not a valid term number</h2>'.format(term)
def user_name(username):
    user_agent = request.headers.get('User-Agent')
    return render_template(
        'vars_and_filters.html',
        president=President(26),
        browser=user_agent,
        username=username.replace('+', ' '),
        fruits=FRUITS,
    )
示例#5
0
def president_by_term(termnum):

    """Retrieve president information for a specified term number"""
    term = int(termnum)
    if 0 < term < 46:
        presidents = [President(term)]
        return render_template('president_results.html', presidents=presidents)
    else:
        html_content = '<h2>Sorry,  {} is not a valid term number</h2>'.format(term)
        return html_content
def main():
    s3 = boto3.resource('s3')  # <1>

    for i in range(1, 46):
        p = President(i)
        data = f"{i};{p.first_name};{p.last_name};{p.party}"
        bindata = data.encode()

        obj = s3.Object(WORD_BUCKET_NAME, f"president/{i}")
        obj.put(Body=bindata)
示例#7
0
def format_html_for_president(term_num):
    """Return HTML for one president"""
    p = President(term_num)
    return '''
    <h1>{}: {} {}</h1>
    <h2>Born in: {}</h2>
    <h2>Lived: {} to {}</h2>
    <h2>Party: {}</h2>
    '''.format(term_num, p.first_name, p.last_name, p.birth_state,
               p.birth_date, p.death_date, p.party)
def president_by_last_name(last_name):
    """Retrieve president information for a specified last name;
        May return info for more than one president
    """
    presidents = []
    for i in xrange(1, 45):
        p = President(i)
        if p.last_name.lower() == last_name.lower():
            presidents.append(p)

    if presidents:
        return render_template('president_results.html', presidents=presidents)
    else:
        return '<h2>Sorry,  {} not found</h2>'.format(last_name)
示例#9
0
def president_by_last_name(last_name):
    """Retrieve president information for a specified last name;
        May return info for more than one president
    """
    html_content = ''
    for i in range(1, 46):
        p = President(i)
        if p.last_name.lower() == last_name.lower():
            html_content += format_html_for_president(i)

    if html_content:
        return html_content
    else:
        return '<h2>Sorry,  {} not found</h2>'.format(last_name)
def index():
    """Main (and only) page; returns list of all presidents"""
    presidents = []
    for i in range(1, 46):
        presidents.append(President(i))
    accept_type = request.headers.get('ACCEPT')
    response = ''
    print("Accept type:", accept_type)
    if accept_type.startswith('text/html'):
        response = render_template('president_list_bs.html',
                                   presidents=presidents)
    elif accept_type.startswith('application/xml'):
        response = pres_list_to_xml(presidents)
    elif accept_type == 'application/json':
        presidents_as_dicts = [pres_to_dict(p) for p in presidents]
        response = jsonify(presidents=presidents_as_dicts)
    # handle error here if non-expected type

    return response
示例#11
0
class Bank:
    name = str(None)
    address = str('Endereço: ')
    street = str('Rua Oswaldo Luiz da Silva,')
    number = str('número 585,')
    neighborhood = str('bairro Jd. Lugar Nenhum,')
    state = str('estado Sem Saber - (SS).')

    def __init__(self, bank_name, president_name):
        self.set_name(bank_name)
        self.president = President(president_name, self)

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_address(self):
        return self.street, self.number, self.neighborhood, self.state

    def get_president(self):
        return self.president.get_name()
示例#12
0
#!/usr/bin/env python

from president import President
"""
Monkey-patch the President class to add a method get_full_name which returns a single string consisting of the first name and the last name, separated by a space.
Try This_: Instead of a method, make full_name a property.
"""


@property
def full_name(self):
    return f"{self.first_name}-{self.last_name}"


setattr(President, "full_name", full_name)

p = President(1)
print(p.full_name)
示例#13
0
 def test_invalid_term_raises_error(self):
     for invalid_term in -1, 0, 46, 1000:
         with self.assertRaises(ValueError):
             p = President(invalid_term)
示例#14
0
 def setUp(self):  # run before each test
     self.pres = President(1)
示例#15
0
 def test_president_one_last_name_is_george(self):
     p = President(1)
     self.assertEqual(p.first_name, "George", "President 1's first name is not George")
示例#16
0
def test_president_one_is_gw():
    p = President(1)
    assert p.first_name == 'George'
    assert p.last_name == 'Washington'
示例#17
0
# Exercise 3-1

from president import President

# Tests President object class.
for term in 1, 26, 39, 45:
    p = President(term)
    print("{} {} was born at {}, {} on {}".format(p.first_name, p.last_name,
                                                  p.birth_place, p.birth_state,
                                                  p.birth_date))
    print()
示例#18
0
#!/usr/bin/python

from president import President


def fn(self):
    return '%s %s' % (self.first_name, self.last_name)


setattr(President, 'get_full_name', fn)
# or just
# President.getFullName = fn

abe = President(16)
print(abe.get_full_name())

millard = President(13)
print(millard.get_full_name())
def test_president_one_last_name_is_george():
    p = President(1)
    assert p.first_name == "George"
示例#20
0
import re
from president import President

p = President(26)
print(type(p))

fields_wanted = ['first_name', 'last_name', 'favorite_beatle']

print(p.first_name)

for field in fields_wanted:
    if hasattr(p, field):
        print(field, getattr(p, field))
    else:
        print(field, "is not an attribute")

print(dir(p))

name_fields = [attr for attr in dir(p) if re.search('name', attr, re.I)]
print(name_fields)


def gfn(self):
    return f"{self.first_name} {self.last_name}"


setattr(President, "get_first_name", gfn)

print(p.get_first_name())
print()
示例#21
0
 def test_invalid_term_raises_error(self):
     with self.assertRaises(ValueError):
         p = President(99)
示例#22
0
def list_presidents():
    """Return list of all presidents"""
    presidents = []
    for i in range(1, 45):
        presidents.append(President(i))
    return render_template('president_list_bs.html', presidents=presidents)
示例#23
0
#!/usr/bin/env python
from president import President

p = President(26)

print(p)

print(p.first_name, p.last_name)

field_name = "birth_place"

field_value = getattr(p, field_name, "NO SUCH ATTRIBUTE, DUDE!")
print(field_value, '\n')

for attr in "first_name", "birth_state", "favorite_color", "party", "gender":
    print(attr, hasattr(p, attr))
print()


def print_stuff(obj):
    if hasattr(obj, "print"):
        obj.print()
    else:
        print(f"sorry, {obj} cannot print")


print_stuff(p)

print(p.party)

delattr(President, "party")
#!/usr/bin/env python
from president import President

for term in 1, 26, 39, 45:
    p = President(term)  # George Washington

    print("{} {} was born at {}, {} on {}".format(p.first_name, p.last_name,
                                                  p.birth_place, p.birth_state,
                                                  p.birth_date))
    print()
示例#25
0
#!/usr/bin/env python

from president import President

def fn(self):
    return '{0} {1}'.format(self.FirstName,self.LastName)
    
setattr(President,'getFullName',fn)
# or just
# President.getFullName = fn

abe = President(16)
print abe.getFullName()

george = President(1)
print george.getFullName()
示例#26
0
#!/usr/bin/env python

from president import President
"""
Write a main script to exercise some or all of the properties from president.py. 
It could look something like
    from president import President
    
    p = President(1)   # George Washington
    print("George was born at {0}, {1} on {2}".format(
        p.birth_place, p.birth_state, p.birth_date
    )
"""
with open('data/presidents.txt') as pres_in:
    for line in pres_in:
        print(line)
        p = President(line[0])
示例#27
0
#!/usr/bin/env python

from president import President

p = President(44)

print(f'President {p.first_name} {p.last_name}, the {p.term_number}th president, was born in {p.birth_city} {p.birth_state}')
示例#28
0
from president import President

p = President(26)

print(p.first_name, p.last_name)

attrs = [a for a in dir(p) if not a.startswith('_')]

print(attrs, '\n')

for attr in attrs:
    print(attr, getattr(p, attr))
print()

#  getattr() hasattr() setattr() delattr()


def get_full_name(self):
    return f"{self.first_name} {self.last_name}"


setattr(President, "get_full_name", get_full_name)

print(p.get_full_name())

setattr(p, 'assassinated', False)

print(p.assassinated)


def serialize(obj):
def test_date_fields_return_dates_or_none(term_number):
    p = President(term_number)
    assert isinstance(p.birth_date, date) or p.birth_date is None
    assert isinstance(p.death_date, date) or p.death_date is None
    assert isinstance(p.term_start_date, date) or p.term_start_date is None
    assert isinstance(p.term_end_date, date) or p.term_end_date is None
示例#30
0
#!/usr/bin/env python

from president import President

for pres_term in 1, 26, 37:
    p = President(pres_term)

    lastname = getattr(p, 'last_name')
    firstname = getattr(p, 'first_name')
    party = getattr(p, 'party')
    print(firstname, lastname, 'was a', party)
def test_invalid_term_raises_error(invalid_term):
    with pytest.raises(ValueError):
        p = President(invalid_term)