generated from mwc/lab_riddles
One internet-enabled service I use regularly is Google Classroom. I often will post an assignment, students can view the assignement, then submit their work online. I hypothesize that when I post an assignment, my computer sends an HTTP POST request to the Google Classroom server. When students view the assignment, their computers send an HTTP GET request to the server to retrieve the assignment details, which are then displayed on their screens. When students submit their work, another HTTP POST request is sent to the server with their submission data, which is then stored and associated with their account. This lab's exploration of requests and responses has helped me understand what happens behind the scenes when I use technology or any platform.I now understand that every time I interact with an app or website, there are multiple HTTP requests and responses happening.
65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
# RiddleAPI
|
|
# ---------
|
|
# By Chris Proctor
|
|
# The Riddle API takes care of connecting to the server.
|
|
|
|
import requests
|
|
from random import choice
|
|
|
|
class APIError(Exception):
|
|
"A custom error we'll use when something goes wrong with the API"
|
|
|
|
class RiddleAPI:
|
|
"Provides an easy way for Python programs to interact with a Riddle Server"
|
|
def __init__(self, server_url):
|
|
self.server_url = server_url
|
|
|
|
def get_all_riddles(self):
|
|
"Fetches all the riddles from the server"
|
|
route = "/all"
|
|
response = requests.get(self.server_url + route)
|
|
if response.ok:
|
|
return response.json()['riddles']
|
|
else:
|
|
raise APIError(response.json()['errors'])
|
|
|
|
def guess_riddle(self, riddle_id, guess):
|
|
"Submits a guess to the server. Returns True or False"
|
|
route = "/guess"
|
|
params = {'id': riddle_id, 'answer': guess}
|
|
response = requests.post(self.server_url + route, json=params)
|
|
if response.ok:
|
|
return response.json()
|
|
else:
|
|
raise APIError(response.json()['errors'])
|
|
|
|
def get_riddle(self, riddle_id):
|
|
"Fetches a single riddle from the server"
|
|
route = "/show"
|
|
params = {'id': riddle_id}
|
|
response= requests.get(self.server_url + route, params=params)
|
|
if response.ok:
|
|
return response.json()
|
|
else:
|
|
raise APIError(response.json()['errors'])
|
|
|
|
def get_random_riddle(self):
|
|
"Fetches all riddles from the server and then randomly returns one"
|
|
riddles = self.get_all_riddles()
|
|
return choice(riddles)
|
|
# raise NotImplementedError("The API doesn't support `get_random_riddle` yet. Can you add it?")
|
|
|
|
def add_riddle(self, question, answer):
|
|
"Adds a new riddle to the server"
|
|
route = "/new"
|
|
params = {'question': question, 'answer': answer}
|
|
response = requests.post(self.server_url + route, json=params)
|
|
if response.ok:
|
|
return response.json()
|
|
else:
|
|
raise APIError(response.json()['errors'])
|
|
|
|
|
|
|
|
|