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: 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 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 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, 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 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 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 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 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)