Skip to content

update fork #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions assignments/session01/echo_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python

import socket
import sys

Expand All @@ -6,16 +8,16 @@ def client(msg, log_buffer=sys.stderr):
server_address = ('localhost', 10000)
# TODO: Replace the following line with your code which will instantiate
# a TCP socket with IPv4 Addressing, call the socket you make 'sock'
sock = None
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_TCP)
print >>log_buffer, 'connecting to {0} port {1}'.format(*server_address)
# TODO: connect your socket to the server here.

sock.connect(server_address)
# this try/finally block exists purely to allow us to close the socket
# when we are finished with it
try:
print >>log_buffer, 'sending "{0}"'.format(msg)
# TODO: send your message to the server here.

sock.sendall(msg)
# TODO: the server should be sending you back your message as a series
# of 16-byte chunks. You will want to log them as you receive
# each one. You will also need to check to make sure that
Expand All @@ -25,11 +27,17 @@ def client(msg, log_buffer=sys.stderr):
# Make sure that you log each chunk you receive. Use the print
# statement below to do it. (The tests expect this log format)
chunk = ''
print >>log_buffer, 'received "{0}"'.format(chunk)
done = False
while not done:
chunk = sock.recv(16)
if len(chunk) < 16:
done = True
print >>log_buffer, 'received "{0}"'.format(chunk)
finally:
# TODO: after you break out of the loop receiving echoed chunks from
# the server you will want to close your client socket.
print >>log_buffer, 'closing socket'
sock.close()


if __name__ == '__main__':
Expand All @@ -39,4 +47,4 @@ def client(msg, log_buffer=sys.stderr):
sys.exit(1)

msg = sys.argv[1]
client(msg)
client(msg)
23 changes: 15 additions & 8 deletions assignments/session01/echo_server.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python

import socket
import sys

Expand All @@ -7,16 +9,17 @@ def server(log_buffer=sys.stderr):
address = ('127.0.0.1', 10000)
# TODO: Replace the following line with your code which will instantiate
# a TCP socket with IPv4 Addressing, call the socket you make 'sock'
sock = None
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_TCP)
# TODO: Set an option to allow the socket address to be reused immediately
# see the end of http://docs.python.org/2/library/socket.html

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# log that we are building a server
print >>log_buffer, "making a server on {0}:{1}".format(*address)

# TODO: bind your new sock 'sock' to the address above and begin to listen
# for incoming connections

sock.bind(address)
sock.listen(1)
try:
# the outer loop controls the creation of new connection sockets. The
# server will handle each incoming connection one at a time.
Expand All @@ -28,7 +31,7 @@ def server(log_buffer=sys.stderr):
# the client so we can report it below. Replace the
# following line with your code. It is only here to prevent
# syntax errors
addr = ('bar', 'baz')
conn, addr = sock.accept()
try:
print >>log_buffer, 'connection - {0}:{1}'.format(*addr)

Expand All @@ -41,29 +44,33 @@ def server(log_buffer=sys.stderr):
# following line with your code. It's only here as
# a placeholder to prevent an error in string
# formatting
data = ''
data = conn.recv(16)
print >>log_buffer, 'received "{0}"'.format(data)
# TODO: you will need to check here to see if any data was
# received. If so, send the data you got back to
# the client. If not, exit the inner loop and wait
# for a new connection from a client
if len(data) > 0:
conn.sendall(data)
else:
break

finally:
# TODO: When the inner loop exits, this 'finally' clause will
# be hit. Use that opportunity to close the socket you
# created above when a client connected. Replace the
# call to `pass` below, which is only there to prevent
# syntax problems
pass
conn.close()

except KeyboardInterrupt:
# TODO: Use the python KeyboardIntterupt exception as a signal to
# close the server socket and exit from the server function.
# Replace the call to `pass` below, which is only there to
# prevent syntax problems
pass
sock.close()


if __name__ == '__main__':
server()
sys.exit(0)
sys.exit(0)
2 changes: 2 additions & 0 deletions assignments/session01/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python

from cStringIO import StringIO
from echo_client import client
import socket
Expand Down
35 changes: 29 additions & 6 deletions assignments/session02/http_server.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
#!/usr/bin/env python

import socket
import sys
from os import path
import os
import mimetypes


def response_ok():
def response_ok(body="", mimetype='text/plain'):
"""returns a basic HTTP response"""
resp = []
resp.append("HTTP/1.1 200 OK")
resp.append("Content-Type: text/plain")
resp.append("Content-Type: " + mimetype)
resp.append("")
resp.append("this is a pretty minimal response")
resp.append(body)
return "\r\n".join(resp)


Expand All @@ -19,14 +24,30 @@ def response_method_not_allowed():
resp.append("")
return "\r\n".join(resp)

def response_not_found():
"""returns a 404 response"""
resp = []
resp.append("HTTP/1.1 404 Not Found")
resp.append("")
return "\r\n".join(resp)

def parse_request(request):
first_line = request.split("\r\n", 1)[0]
method, uri, protocol = first_line.split()
if method != "GET":
raise NotImplementedError("We only accept GET")
print >>sys.stderr, 'request is okay'
return uri

def resolve_uri(uri):
fullPath = 'webroot/%s' % uri
if not path.exists(fullPath):
raise ValueError
if path.isdir(fullPath):
return ['\r\n'.join(os.listdir(fullPath)),'text/plain']
elif path.isfile(fullPath):
mType = mimetypes.guess_type(fullPath)
return [open(fullPath,'rb').read(),mType[0]]

def server():
address = ('127.0.0.1', 10000)
Expand All @@ -50,11 +71,13 @@ def server():
break

try:
parse_request(request)
uri = parse_request(request)
mType, body = resolve_uri(uri)
response = response_ok(body,mType)
except NotImplementedError:
response = response_method_not_allowed()
else:
response = response_ok()
except ValueError:
response = response_not_found()

print >>sys.stderr, 'sending response'
conn.sendall(response)
Expand Down
2 changes: 2 additions & 0 deletions assignments/session02/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python

import mimetypes
import os
import socket
Expand Down
42 changes: 42 additions & 0 deletions assignments/session03/instructions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
this will print the top 20 ski resorts and their closest hospital. you can pass in a single location argument like "washington state" or "canada". if you do not pass in an argument, then the default location is "united states"

example. ./leblanc_mashup.py "washington state"

output:

(soupenv)adam@adam-UL50VT:~/Python_Course/Python_200/assignments/session03$ ./leblanc_mashup.py "washington state"
looking for ski resorts in washington state
results

Ski Resort:
Name: Stevens Pass
Address: South 2 Street, Skykomish, Washington, United States
Lat: 47.74443 Lon: -121.089282
Closest Hospital:
Name: Cascade Medical Center
Address: 817 Commercial Street, Leavenworth, WA, United States
Distance: 35.30 miles


Ski Resort:
Name: White Pass
Address: 48935 U.S. 12, Naches, WA, United States
Lat: 46.637501 Lon: -121.390556
Closest Hospital:
Name: Women's Health Network
Address: 2205 West Lincoln Avenue, Yakima, WA, United States
Distance: 51.39 miles


Ski Resort:
Name: Mission Ridge Ski & Board Resort
Address: 7500 Mission Ridge Road, Wenatchee, WA, United States
Lat: 47.292446 Lon: -120.399771
Closest Hospital:
Name: Central Washington Hospital
Address: 1201 South Miller Street, Wenatchee, WA, United States
Distance: 12.93 miles

....
....
....
124 changes: 124 additions & 0 deletions assignments/session03/leblanc_mashup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#!/usr/bin/env python

import json
import requests
import sys

googApiKey = r'AIzaSyDIcFETDCpeaAScHDu-1b4qZ-a6rRhXiyk'

class Location(object):
def __init__(self,name,lat,lon,address='N\A'):
self.name = name
self.address = address
self.lat = lat
self.lon = lon

def getSkiResorts(location='united states'):
api_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
print 'looking for ski resorts in %s' % location
location = location.replace(' ','+')

parameters = {
'sensor':'false',
'types':'establishment|lodging',
'query':'ski+resort+%s' % location,
'key':googApiKey}

resp = requests.get(api_url,params=parameters)
data = json.loads(resp.text)
resorts = []
if data['status'] == 'OK':
for result in data['results']:
tmpName = result['name']
tmpLat = result['geometry']['location']['lat']
tmpLon = result['geometry']['location']['lng']
tmpAddr = result['formatted_address']
if tmpName and tmpLat and tmpLon:
resorts.append(Location(tmpName,tmpLat,tmpLon,tmpAddr))

return resorts


def getDistance(orgLat,orgLon,destLat,destLon):
api_url = 'http://maps.googleapis.com/maps/api/directions/json'
m_to_ft = 3.281

parameters = {
'sensor':'false',
'origin':'%s,%s'%(orgLat,orgLon),
'destination':'%s,%s' % (destLat,destLon)}

resp = requests.get(api_url,params=parameters)
data = json.loads(resp.text)
distance = None
if data['status'] == 'OK':
meters = data['routes'][0]['legs'][0]['distance']['value']
distance = meters * m_to_ft

return distance

def findClosestHospital(lat,lon):
api_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
miles_to_ft = 5280

parameters = {
'sensor':'false',
'types':'establishment',
'location':'%s,%s'%(lat,lon),
'query':'hospital',
'radius':'16000',
'key':googApiKey}

resp = requests.get(api_url,params=parameters)
data = json.loads(resp.text)
hospital = None
distance = None
if data['status'] == 'OK':
for result in data['results']:
tmpName = result['name']
tmpLat = result['geometry']['location']['lat']
tmpLon = result['geometry']['location']['lng']
tmpAddr = result['formatted_address']
tmpDist = getDistance(lat,lon,tmpLat,tmpLon)
if tmpName and tmpLat and tmpLon and tmpDist:
if not distance or tmpDist < distance:
hospital = Location(tmpName,tmpLat,tmpLon,tmpAddr)
distance = tmpDist

if distance:
if distance > miles_to_ft:
distance = '%.2f miles' % float(distance / miles_to_ft)
else:
distance = '%d feet' % distance

return hospital,distance



if __name__ == '__main__':
if len(sys.argv) == 2:
location = sys.argv[1]
else:
location = 'united states'

output = []
for resort in getSkiResorts(location):
hospital,dist = findClosestHospital(resort.lat,resort.lon)
output.append('Ski Resort:')
output.append('\tName: %s' % resort.name)
output.append('\tAddress: %s' % resort.address)
output.append('\tLat: %s Lon: %s' % (resort.lat,resort.lon))
if hospital:
output.append('\tClosest Hospital:')
output.append('\t\tName: %s' % hospital.name)
output.append('\t\tAddress: %s' % hospital.address)
if dist:
output.append('\t\tDistance: %s' % dist)
else:
output.append('\t\tDistance: N\A')
else:
output.append('\tClosest Hospital: N\A')
output.append('\r\n')
print 'results'
print
print '\r\n'.join(output)
Loading