Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
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
17 changes: 12 additions & 5 deletions 17 assignments/session01/echo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ 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)
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
Expand All @@ -24,13 +26,18 @@ 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 = True
while done:
chunk = sock.recv(16)
print >>log_buffer, 'received "{0}"'.format(chunk)
if len(chunk) < 16:
done = False
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__':
if len(sys.argv) != 2:
Expand All @@ -39,4 +46,4 @@ def client(msg, log_buffer=sys.stderr):
sys.exit(1)

msg = sys.argv[1]
client(msg)
client(msg)
20 changes: 13 additions & 7 deletions 20 assignments/session01/echo_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ 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)
# 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 +30,8 @@ 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,32 @@ 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
conn.sendall(data)
if len(data)<16:
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)
39 changes: 32 additions & 7 deletions 39 assignments/session02/http_server.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,35 @@
import socket
import sys
import os
import mimetypes


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

def resolve_uri(uri):
base = 'webroot'
fileName = os.path.join(base, uri.lstrip('/'))
if os.path.isfile(filename):
mimetype = mimetypes.guess_type(fileName)[0]
body = open(filename, 'rb').read()
return body, mimetype
elif os.path.isdir(fileName):
bk = "\n".join(os.listdir(fileName))
return bk, 'text/ plain'
else:
return 'File Not Found'

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

def response_method_not_allowed():
"""returns a 405 Method Not Allowed response"""
Expand All @@ -19,13 +38,13 @@ def response_method_not_allowed():
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 server():
Expand All @@ -50,11 +69,17 @@ def server():
break

try:
parse_request(request)
uri = parse_request(request)
body, mimetype = resolve_uri(uri)

except NotImplementedError:
response = response_method_not_allowed()

except ValueError:
response = response_not_found()

else:
response = response_ok()
response = response_ok(body, mime)

print >>sys.stderr, 'sending response'
conn.sendall(response)
Expand Down
92 changes: 92 additions & 0 deletions 92 assignments/session03/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
Session 3 Homework
==================

#Assignment #3 Mashup

#This was a enjoyable assignment that I learned a lot from. I tried to do a few more complicated tasks, but ran out of time.

#This program is custom NPR News feed. It returns all my local npr station info and the full text, images, and audio of the news stories I'm interested in. But since sometimes the news is hard I also mashed in some imageges of kittens.

#You should just be able to run this code.

from urllib2 import urlopen
from json import load, dumps

#NPR Key
key = "MDEyNTA4NzYxMDEzODMzMjY0NDQ5YTg4MQ001"

def build_api_call(key, zip_code):
url = 'http://api.npr.org/stations?apiKey=' + key
url+='&format=json'
url += "&zip=" + str(zip_code)
return url

def call_station_api(url):
response = urlopen(url)
j = load(response)
return j

def parse_station_json(json_obj):
for station in json_obj['station']:
print (station['callLetters']['$text']+ ": " +
station['marketCity']['$text'] + ", " +
station['state']['$text'])
print "Frequency:" , station['frequency']['$text'] , station['band']['$text']

if 'url' in station:
print "MP3 Streams: "
for link in station['url']:
if link["type"] == "Audio MP3 Stream":
print "\t" , link["title"], " - " , link["$text"]

def NPR_Stories(key, subject):
url = 'http://api.npr.org/query?apiKey='
url = url + key
url += '&numResults=10&format=json'
url += '&id=' + str(subject) +'&requiredAssets=image,text,audio'
response = urlopen(url)
json_obj = load(response)

f = open('output.json', 'w')
f.write(dumps(json_obj, indent=4))
f.close()

for story in json_obj['list']['story']:
print "TITLE: " + story['title']['$text'] + "\n"
print "DATE: " + story['storyDate']['$text'] + "\n"
print "TEASER: " + story['teaser']['$text'] + "\n"

if 'byline' in story:
print "BYLINE: " + story['byline'][0]['name']['$text'] + "\n"
if 'show' in story:
print "PROGRAM: " + story['show'][0]['program']['$text']+"\n"
print "NPR URL: " + story['link'][0]['$text'] +"\n"
print "IMAGE: " +story['image'][0]['src'] +"\n"
if 'caption' in story:
print "IMAGE CAPTION: " +story['image'][0]['caption']['$text'] +"\n"
if 'producer' in story:
print 'IMAGE CREDIT: ' + story['image'][0]['producer']['$text'] +"\n"
print "MP3 AUDIO: " + story['audio'][0]['format']['mp3'][0]['$text'] +"\n"
for paragraph in story['textWithHtml']['paragraph']:
print paragraph['$text'] + "\n"

def kittens():
url = 'http://placekitten.com/250/250'
kitten = urlopen(url).read()
f = open('kittens.jpeg', 'w')
f.write(kitten)
print f
f.close()


if __name__ =='__main__':
url = build_api_call(key, 98115)
kittens()
print "URL: ", url
json_obj = call_station_api(url)
kittens()
parse_station_json(json_obj)
kittens()
NPR_Stories(key, 1049)


38 changes: 0 additions & 38 deletions 38 assignments/session03/tasks.txt

This file was deleted.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.