def delete(self, request_id, response_id): """ purpose: Delete an individual response linked to a specific request parameters: response_id - ID of response request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid id HTTP 201 - Deleted request; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Store data before deleting resp_data = responseSchema.dump(response) response.delete() return HTTPHandler.valid_data(resp_data) except Exception as e: return HTTPHandler.error(e)
def delete(self, request_id): """ purpose: Delete all responses linked to a specific request parameter: request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid ids HTTP 201 - List of deleted responses; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Dump response data pertaining to responses that will be deleted resps = responsesSchema.dump(request.responses) # Delete responses Response.query.with_parent(request).delete() db.session.commit() return HTTPHandler.valid_data(resps) except Exception as e: return HTTPHandler.error(e)
def delete(self, request_id): """ purpose: Delete an individual request parameters: request_id - ID of request return: HTTP 400 - Error occured HTTP 422 - Invalid id HTTP 201 - Deleted request; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Dump before deleting so reference still exists request_result = requestSchema.dump(request) request.delete() return HTTPHandler.valid_data(request_result) except Exception as e: return HTTPHandler.error(e)
def get(self, request_id, response_id): """ purpose: Get all ratings for a response parameters: response_id - ID of response to get ratings from request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid ids HTTP 201 - List of ratings; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Get all ratings ratings = Rating.query.with_parent(response) ratings = ratingsSchema.dump(ratings) return HTTPHandler.valid_data(ratings) except Exception as e: return HTTPHandler.error(e)
def get(self, request_id, response_id): """ purpose: Get a response linked to a specific request parameter: response_id - ID of response request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid ids HTTP 201 - Response; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') return HTTPHandler.valid_data(responseSchema.dump(response)) except Exception as e: return HTTPHandler.error(e)
def post(self): """ purpose: Send email to inbox for contact purposes Send email to user thanking them for their feedback parameters: Name Email Subject Message return: HTTP 400 - Error occured HTTP 200 - Successful """ # Get JSON data json_data = req.get_json(force=False) print(json_data) if not json_data: return HTTPHandler.no_data() # Load contact data if possible try: data = contactSchema.load(json_data) except ValidationError as e: return HTTPHandler.improper_data(e) contact_failed = False # Send message confirming contact try: mail.send_message(subject='SafeWalk - Message Received', sender='*****@*****.**', recipients=[data['email']], body=create_user_message(data['name'], data['email'], data['subject'], data['message'])) except Exception as e: contact_failed = True print(e) # If contact to user did not fail, forward message to safewalks account if not contact_failed: try: mail.send_message(subject='SafeWalk - New Message', sender='*****@*****.**', recipients=['*****@*****.**'], body=create_account_message( data['name'], data['email'], data['subject'], data['message'])) except Exception as e: print(e) #[email protected] #walksafe1119! return HTTPHandler.valid()
def get(self): """ purpose: Get all requests; including all responses and ratings parameters: None return: HTTP 400 - Error occured HTTP 201 - Successful, json = { 'status': 'success', 'data' : [ { request data ... 'responses': [ { response data... 'ratings' = [ { rating data... }, ] }, ] }, ] } """ try: # Get requests as database object and JSO requests_db = Request.query.all() requests = requestsSchema.dump(requests_db) # For each request, link response and rating JSON for i in range(len(requests)): # Get responses as database object and JSON responses_db = Response.query.with_parent(requests_db[i]) responses = responsesSchema.dump(responses_db) # For each response, link rating JSON for j in range(len(responses)): rating = Rating.query.with_parent(responses_db[j]) rating = ratingsSchema.dump(rating) responses[j]['ratings'] = rating requests[i]['responses'] = responses return HTTPHandler.valid_data(requests) except Exception as e: return HTTPHandler.error(e)
def get(self, id): """ purpose: Get a requests by ID; including all responses and ratings parameters: id - request id return: HTTP 400 - Error occured HTTP 422 - Invalid id HTTP 201 - Successful, json = { 'status': 'success', 'data' : request data ... 'responses': [ { response data... 'ratings' = [ { rating data... }, ] }, ] } """ try: # Get request as database object and JSON request_db = Request.query.get(id) if not request_db: return HTTPHandler.improper_id() request = requestSchema.dump(request_db) # Get responses for request as database object and JSON responses_db = Response.query.with_parent(request_db) responses = responsesSchema.dump(responses_db) # For each response, link rating JSON for i in range(len(responses)): rating = Rating.query.with_parent(responses_db[i]) rating = ratingsSchema.dump(rating) responses[i]['ratings'] = rating request['responses'] = responses return HTTPHandler.valid_data(request) except Exception as e: return HTTPHandler.error(e)
def get(self): """ purpose: Get all request resources return: HTTP 400 - Error occured HTTP 201 - List of requests; JSON """ try: requests = Request.get_all() return HTTPHandler.valid_data( requestsSchema.dump(requests) ) except Exception as e: return HTTPHandler.error(e)
def put(self, request_id): """ purpose: Update all response resources pertaining to a specific request parameter: request_id - ID of request that is parent to the response json - json containing Response data: { "overallRating": ... "pathPolyline": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid id or data HTTP 201 - List of updated responses; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load response data if possible try: data = responseSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Update each response linked to the parent request for r in request.responses: r.overallRating = data['overallRating'] r.pathPolyline = data['pathPolyline'] # Save changes db.session.commit() # Return response data return HTTPHandler.valid_data( responsesSchema.dump(request.responses)) except Exception as e: return HTTPHandler.error(e)
def post(self, request_id): """ purpose: Create a new response linked to a specific request parameter: request_id - ID of request that is parent to the response json - json containing Response data: { "overallRating": ... "pathPolyline": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid id or data HTTP 201 - New response; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load response data if possible try: data = responseSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Create new response ID new_response = Response(requestID=request_id, overallRating=data['overallRating'], pathPolyline=data['pathPolyline']) # Link new response with parent request request.responses.append(new_response) new_response.save() # Return newly created response return HTTPHandler.valid_data(responseSchema.dump(new_response)) except Exception as e: return HTTPHandler.error(e)
def put(self, request_id): """ purpose: Update an individual request parameters: request_id - ID of request json - json containing Request data { "timeStamp" : ... "fromLocation": ... "toLocation": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid id or data HTTP 201 - Updated resquest; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load request data if possible try: data = requestSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # If request exists, update data. request.timeStamp = data['timeStamp'] request.fromLocation = data['fromLocation'] request.toLocation = data['toLocation'] db.session.commit() return HTTPHandler.valid_data( requestSchema.dump(request) ) except Exception as e: return HTTPHandler.error(e)
def put(self): """ purpose: Updates all request resources parameters: json - json containing updated Response data { "timeStamp" : ... "fromLocation": ... "toLocation": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid data HTTP 201 - List of updated requests; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load request data if possible try: data = requestSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Get all requests requests = Request.get_all() # Update each request for r in requests: r.timeStamp = data['timeStamp'] r.fromLocation = data['fromLocation'] r.toLocation = data['toLocation'] # Save changes db.session.commit() return HTTPHandler.valid_data( requestsSchema.dump(requests) ) except Exception as e: return HTTPHandler.error(e)
def put(self, request_id, response_id, rating_id): """ purpose: Update an individual rating parameters: rating_id - ID of rating response_id - ID of response that is parent to the rating request_id - ID of request that is parent to the response json - json containing Rating data { 'metricValue': ... 'metricType': ... } return: HTTP 400 - Error occured HTTP 422 - Invalid ids or data HTTP 201 - Updated rating; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load rating data if possible try: data = ratingSchema.load(json_data) except ValidationError as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Get rating by ID rating = Rating.query.with_parent(response).filter( Rating.ID == rating_id).one() if not rating: return HTTPHandler.improper_id('Rating') # Update element and save rating.metricType = data['metricType'] rating.metricValue = data['metricValue'] db.session.commit() return HTTPHandler.valid_data(ratingSchema.dump(rating)) except Exception as e: return HTTPHandler.error(e)
def post(self): """ purpose: Create a new request parameters: json - json containing Request data { "timeStamp" : ... "fromLocation": ... "toLocation": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid data HTTP 201 - New request; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load request data if possible try: data = requestSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Create new request new_request = Request( timeStamp = data['timeStamp'], fromLocation = data['fromLocation'], toLocation = data['toLocation'] ) # Save the new request into the DB new_request.save() return HTTPHandler.valid_data( requestSchema.dump(new_request) ) except Exception as e: return HTTPHandler.error(e)
def delete(self, request_id, response_id, rating_id): """ purpose: Delete an individual rating parameters: rating_id - ID of rating response_id - ID of response that is parent to the rating request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid ids HTTP 201 - Deleted rating; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Get rating by ID rating = Rating.query.with_parent(response).filter( Rating.ID == rating_id).one() if not rating: return HTTPHandler.improper_id('Rating') # Store JSON before deleting instance rating_results = ratingSchema.dump(rating) # Delete rating.delete() return HTTPHandler.valid_data(rating_results) except Exception as e: return HTTPHandler.error(e)
def delete(self): """ purpose: Delete all requests return: HTTP 400 - Error occured HTTP 201 - Deleted requests; JSON """ try: # Returns the requests that will be deleted requests = Request.get_all() requests = requestsSchema.dump(requests) # Delete and save new DB status Request.query.delete() db.session.commit() return HTTPHandler.valid_data(requests) except Exception as e: return HTTPHandler.error(e)
def get(self, request_id): """ purpose: Get an individual request parameters: request_id - ID of request return: HTTP 400 - Error occured HTTP 422 - Invalid id HTTP 201 - Request; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Return data if exists return HTTPHandler.valid_data( requestSchema.dump(request) ) except Exception as e: return HTTPHandler.error(e)
def delete(self, request_id, response_id): """ purpose: Delete all ratings for a given response parameters: response_id - ID of response to delete ratings from request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid ids HTTP 201 - Deleted ratings; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') ratings = ratingsSchema.dump(response.ratings) # Delete all ratings with response as parent Rating.query.with_parent(response).delete() # Update db db.session.commit() return HTTPHandler.valid_data(ratings) except Exception as e: return HTTPHandler.error(e)
def post(self, request_id, response_id): """ purpose: Add new rating to a given response parameters: response_id - ID of response to add rating too request_id - ID of request that is parent to the response json - json containing Rating data { 'metricValue': ... 'metricType': ... } return: HTTP 400 - Error occured HTTP 422 - Invalid ids or data HTTP 201 - Newly added rating; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load rating data if possible try: data = ratingSchema.load(json_data) except ValidationError as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Creating rating element ratingElement = Rating(responseID=response_id, metricType=data['metricType'], metricValue=data['metricValue']) # Add rating element to response response.ratings.append(ratingElement) # Save to database ratingElement.save() return HTTPHandler.valid_data(ratingSchema.dump(ratingElement)) except Exception as e: return HTTPHandler.error(e)
def get(self, request_id): """ purpose: Get all response resources pertaining to a specific request parameter: request_id - ID of request that is parent to the response return: HTTP 400 - Error occured HTTP 422 - Invalid id HTTP 201 - List of responses; JSON """ try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Return response data return HTTPHandler.valid_data( responsesSchema.dump(request.responses)) except Exception as e: return HTTPHandler.error(e)
def put(self, request_id, response_id): """ purpose: Update all ratings for a given response parameters: response_id - ID of response to update ratings for request_id - ID of request that is parent to the response json - json containing updated Rating data { 'metricValue': ... 'metricType': ... } return: HTTP 400 - Error occured HTTP 422 - Invalid ids or data HTTP 201 - List of updated ratings; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load rating data if possible try: data = ratingSchema.load(json_data) except ValidationError as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') # Update rating element for r in response.ratings: r.metricType = data['metricType'] r.metricValue = data['metricValue'] # Save updates db.session.commit() return HTTPHandler.valid_data(ratingsSchema.dump(response.ratings)) except Exception as e: return HTTPHandler.error(e)
def put(self, request_id, response_id): """ purpose: Update a response linked to a specific request parameter: response_id - ID of response request_id - ID of request that is parent to the response json - json containing Response data: { "overallRating": ... "pathPolyline": ... } return: HTTP 400 - Error occured HTTP 422 - Invalid ids or data HTTP 201 - Response; JSON """ # Get json data json_data = req.get_json(force=False) if not json_data: return HTTPHandler.no_data() # Load response data if possible try: data = responseSchema.load(json_data) except Exception as e: return HTTPHandler.improper_data(e) try: # Get request by ID request = Request.query.get(request_id) if not request: return HTTPHandler.improper_id('Request') # Get response by ID response = Response.query.with_parent(request).filter( Response.ID == response_id).one() if not response: return HTTPHandler.improper_id('Response') response.overallRating = data['overallRating'] response.pathPolyline = data['pathPolyline'] db.session.commit() return HTTPHandler.valid_data(responseSchema.dump(response)) except Exception as e: return HTTPHandler.error(e)
def post(self): """ purpose: Get the metrics pertaining to all paths from START to END parameters: json format [REQUIRED] { start: address for geocoding - str OR [LAT, LON] end: address for geocoding - str OR [LAT, LON] debug [optional]: True or False. If true, images of routes are saved in local directory. } return: HTTP 400 - If no JSON provided HTTP 422 - If JSON is formatted improperly HTTP 201 - If successful, json = { "status": "success", "data": [ { "polyline": str, Polyline for rendering "lights": float, Lights per km "sidewalks": float, Sidewalk availability ratio (Sidewalk distance/route distance) "traffic": float, Average daily traffic, weighted "duration": float, Duration of route "distance": float, Distance of route }, ] } """ # Grab JSON data print('Hello') json_data = req.get_json(force=False) print(json_data) if not json_data: print('Hello') return HTTPHandler.no_data() # If exception is thrown, JSON is improperly formatted try: # Grab routes based on start and end start = time.time() routes = gmaps.walking_routes(json_data['start'], json_data['end']) print('To get routes: {}'.format(time.time() - start)) # Calculate maximum bounding box and split that box into smaller boxes for query start = time.time() box_ne, box_sw = max_bounding_box(routes) boxes = split_box(box_ne, box_sw, 25) print('To create boxes: {}'.format(time.time() - start)) # Collect data from opendata portal start = time.time() lights, sidewalks, volumes = datapool.collect(boxes) print('To collect data: {}'.format(time.time() - start)) # Calculate metrics start = time.time() light_density = algos.street_light_density(routes, lights) sidewalk_density = algos.sidewalk_density(routes, sidewalks) volume_density = algos.traffic_density(routes, volumes) print('To run computations: {}'.format(time.time() - start)) data = [] for i in range(len(routes)): r = 'Route {} has {:.2f} lights/km, {:.2f}% sidewalk availability, and {:.2f} cars per day on average'\ .format(i+1, light_density[i], sidewalk_density[i]*100, volume_density[i]) # Format JSON data data.append( {"polyline": str(routes[i].polyline),\ "lights": light_density[i],\ "sidewalks": sidewalk_density[i],\ "traffic": volume_density[i],\ "duration": routes[i].duration,\ "distance": routes[i].distance }) # Save figure data if debug mode is active if json_data.get('debug'): if json_data['debug']: import os from config import basedir from datetime import datetime import matplotlib.pyplot as plt # Colors to cycle through for routes colors = ['blue', 'orange', 'pink', 'purple'] # Create base directory if needed base_location = basedir + '\plots' if not os.path.exists(base_location): os.mkdir(base_location) # Create directory to save current plots if needed save_location = base_location + r'\{}'.format( datetime.now().strftime("%d_%m_%Y-%H_%M_%S")) if not os.path.exists(save_location): os.mkdir(save_location) # Create figure for street lights plt.figure(figsize=(20, 10)) # Plot street lights lights = [l.coord.latlng for l in lights] plt.scatter(*zip(*lights), color='grey', s=1) # Plot routes for i in range(len(routes)): x, y = routes[i].polygon.exterior.xy plt.plot( x, y, color=colors[i % 4], label='Route {} - {:.2f} lights per km'.format( str(i + 1), light_density[i])) # Add legend and save plt.legend(loc="upper left") plt.savefig(save_location + r'\lights.png') # Create figure for sidewalks plt.figure(figsize=(20, 10)) # Plot sidewalks for sidewalk in sidewalks: x, y = sidewalk.line.xy plt.plot(x, y, color='grey', alpha=0.7, linewidth=1, solid_capstyle='round', zorder=2) # Plot routes for i in range(len(routes)): x, y = routes[i].polygon.exterior.xy plt.plot(x, y, color=colors[i % 4], label='Route {} - {:.2f}% sidewalk coverage'. format(str(i + 1), sidewalk_density[i] * 100)) # Add legend and save plt.legend(loc="upper left") plt.savefig(save_location + r'\sidewalks.png') # Create figure for traffic plt.figure(figsize=(20, 10)) # Assign color codes to different volumes of road for volume in volumes: # Default color c = 'black' if volume.volume > 1000 and volume.volume < 5000: c = 'yellow' elif volume.volume > 5000: c = 'red' else: c = 'green' # Plot the line x, y = volume.line.xy plt.plot(x, y, color=c, alpha=1.0, linewidth=1, solid_capstyle='round', zorder=2) # Plot routes for i in range(len(routes)): x, y = routes[i].polygon.exterior.xy plt.plot( x, y, color=colors[i % 4], label='Route {} - {:.2f} average cars per day'. format(str(i + 1), volume_density[i])) # Add legend and save plt.legend(loc="upper left") plt.savefig(save_location + r'\traffic.png') return HTTPHandler.valid_data(data) except Exception as e: print(e) return HTTPHandler.improper_data(e)