INFO 153B/INFO 253B: Backend Web Architecture
Kay Ashaolu
def save_def(word, definition):
# ...
# working code
# ...
return
def get_def(word):
# ...
# working code
# ...
return definition
# local.py: Local Implementation of API
dictionary = {}
def save_def(word, definition):
dictionary[word] = definition
def get_def(word):
return(dictionary[word])
<a class="styles--weatherData--24HO9 weather-data Button--default--2gfm1" href="/weather/today/l/c6e9a92db240946a7b8379f2177f4d7613047e97ecb1192810d1a0c69f4c97f9"
target="_self" data-from-string="locationCard"><svg set="weather" skycode="31" theme="full" name="" class="Icon--icon--2aW0V Icon--fullTheme--3Fc-5"
data-testid="Icon" viewBox="0 0 200 200"><title>Clear Night</title><use xlink:href="#svg-symbol-moon" transform="matrix(2.07 0 0 2.07 -72 3)"></use>
<use xlink:href="#svg-symbol-star" transform="translate(-4 -1)"></use>
<use xlink:href="#svg-symbol-star" transform="matrix(.8 0 0 .8 62 78)">
</use></svg><span class="styles--temperature--3YaGV">35°</span></a>
/* save_def input data */
{
word: "baby",
definition: "A small person"
}
/* get_def output data */
{
definition: "A small person"
}
/* sample weather data*/
{
temp: "35",
unit: "Farenheit"
}
# api.py
from flask import Flask, request, Response
import json
import logging
app = Flask(__name__)
dictionary = {}
@app.route('/save_def', methods=["POST"])
def save_def():
if request.headers['Content-Type'] == 'application/json':
arguments = request.get_json()
word = arguments.get("word")
definition = arguments.get("definition")
dictionary[word] = definition
logging.info("Word {} with definition {} saved".format(word, definition))
else:
logging.warning("Invalid content type: only application/json is allowed")
resp = Response('')
return resp
@app.route('/get_def/<word>', methods=["GET"])
def get_def(word):
# Note for GET Request, we get input parameters from URL, not
# application/json
# request body
if word not in dictionary:
definition = "Not Found"
logging.warning("{} not found in dictionary".format(word))
else:
definition = dictionary[word]
data = {"word": word, "definition": definition}
resp = Response(json.dumps(data), mimetype='application/json')
return resp
# client.py
import requests
import json
server_url = "http://localhost:5050"
def save_def(word, definition):
headers = {'Content-Type': 'application/json'}
data = {"word": word, "definition": definition }
url = f"{server_url}/save_def"
r = requests.post(url, data=json.dumps(data), headers=headers)
def get_def(word):
headers = {'Accept':'application/json'}
url = f"{server_url}/get_def/{word}"
r = requests.get(url, headers=headers)
data = r.json()
return data["definition"]
if __name__ == "__main__":
print("Saving the definition: country: a nation with its own government, occupying a particular territory.")
save_def(word="country", definition="a nation with its own government, occupying a particular territory.")
print()
print("Retrieving the definition of 'country'")
print(get_def("country"))