Question: Use the REST_server.py and REST_Client.py to implement a Loan Calculator in Python. REST SERVER.PY import re from http.server import HTTPServer, BaseHTTPRequestHandler import logging from json
Use the REST_server.py and REST_Client.py to implement a Loan Calculator in Python.
REST SERVER.PY
import re from http.server import HTTPServer, BaseHTTPRequestHandler import logging from json import loads, dumps from tickets import create_ticket from db_util.db_help import get_loan_for_loan_id, get_owner_id_for_ticket
class RestHandler(BaseHTTPRequestHandler):
def get_data(self): if 'content-length' in self.headers: data=self.rfile.read(int(self.headers['content-length'])) logging.info('data is '+data.decode()) return loads(data) else: logging.debug('no content lenght') return {}
def send_data(self, rtdata): # take rtdata, and create and send a response self.send_response(200) self.send_header('content-type', "application/json") rt=dumps(rtdata).encode() self.send_header('content-length', len(rt)) self.end_headers() self.wfile.write(rt)
def send_error_message(self, message, status_code=412): self.send_response(status_code) self.send_header('content-type', "application/json") rt = dumps({'error': message}).encode() self.send_header('content-length', len(rt)) self.end_headers() self.wfile.write(rt)
def do_GET(self): if re.fullmatch("/loan/(\\d+)", self.path): data=self.get_data() if 'ticket' in data: ticket=data['ticket'] # data={'ticket': 'o1u4hfjasdfkah3iurhf'} # data['ticket']=>'o1u4hfjasdfkah3iurhf' else: ticket=None if ticket: # parse the path to obtain loan_id match=re.fullmatch("/loan/(\\d+)", self.path) loan_id=int(match.group(1)) # client request= "GET /loan/1" # match=/loan/1 # group(1)=1 # client request= "GET /loan/4" # group(2)=4
# send query to the DB to obtain loan information where # loan_id=1 the_loan=get_loan_for_loan_id(loan_id) if the_loan: # check the_loan and the ticket have the same owner oid=get_owner_id_for_ticket(ticket) if oid==the_loan['owner']: # send the_loan back to the client self.send_data({'loan':the_loan}) else: self.send_error_message("no permission to access to the loan info.") else: self.send_error_message("no loan data found") else: self.send_error_message("ticket required for operation")
def do_POST(self): # implementing "Request a ticket" operation. # POST, /owner/ticket # 1. How to get the path from the request object. print(self.path) # 2. check that the path satisfies the pattern if re.fullmatch("/owner/ticket", self.path): # 3. get the owner name from the request body data=self.get_data() #{'owner_name': 'Alice'} owner_name=data.get('owner_name') #owner_name=data['owner_name'] print(owner_name) if owner_name: # 4. check the validity of the owner name # create a ticket ticket=create_ticket(owner_name) if ticket: # create a response: intial line, headers, and body # send the response back to the client self.send_data({'ticket':ticket}) else: # the name of owner was invalid self.send_error_message("invalid owner name:"+str(owner_name)) else: self.send_error_message("didn't receive a valid owner name:" + str(owner_name)) pass elif re.fullmatch("/owner",self.path): pass elif re.fullmatch("/loan", self.path): pass else: self.send_error_message("invalid path:" + str(self.path))
#create_owner #create_loan
def do_PUT(self): pass def do_DELETE(self): pass
if __name__=="__main__": server=HTTPServer(('',8080), RestHandler) server.serve_forever()
REST_CLIENT.PY
import requests
data={'owner_name':'Alice'}
response=requests.post("http://localhost:8080/owner/ticket", json=data)
response_dic=response.json()
print(response_dic) print(response_dic.get('ticket')) print(response_dic['ticket'])
if 'ticket' in response_dic: ticket=response_dic['ticket'] print(ticket) #data2={'ticket':ticket} response2=requests.get("http://localhost:8080/loan/1", json=response_dic) print(response2) print(response2.text)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
