def get(user_id): try: user = db_session().query(User).filter_by(id=user_id).first() if user: user_kilometers = 0 trip_list = db_session().query(Trip).filter_by(user_id=user_id).all() for trip in trip_list: start_kilometers = trip.first_odometer_in_meters / 1000.0 end_kilometers = trip.last_odometer_in_meters / 1000.0 user_kilometers += (end_kilometers - start_kilometers) achievement_list = db_session().query(AchievementUser).filter_by(user_id=user_id).all() achievement_list = [achievement_user.achievement.serialize() for achievement_user in achievement_list] response = { 'user': user.serialize(), 'kilometers': round(user_kilometers, 2), 'trips': len(trip_list), 'average': round(user_kilometers / len(trip_list), 2), 'achievements': achievement_list } return jsonify(error=False, response=response), 200 else: return jsonify(error=True, message='No user found with {} as id.'.format(user_id)), 400 except Exception as e: log.error('Unexpected error in GET/statistics: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(participant_id): try: participant = db_session().query(Participant).filter_by( id=participant_id).first() if participant: if participant.route_id: origin = participant.origin destination = participant.trip.destination route_path = participant.route.route way_points_array = [] for idx, stop in enumerate(route_path.split(',')): participant = db_session().query(Participant).filter_by( id=stop).first() if not idx: origin = participant.origin else: way_points_array.append( {'location': participant.origin}) response = dict(origin=origin, destination=destination, waypoints=way_points_array) return jsonify(error=False, response=response), 200 else: return jsonify( error=True, message='No route found for this participant.'), 400 else: return jsonify( error=True, message='No participant found with {} as id.'.format( participant_id)), 400 except Exception as e: log.error('Unexpected error in GET/route: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def login_post(): try: body = request.json required_parameters = ['email', 'password'] if not all(x in body for x in required_parameters): return jsonify(error=True, message='{} are required parameters.'.format( required_parameters)), 400 username, domain = body['email'].lower().split('@') company = domain.split('.')[0] user = db_session().query(User).filter_by(username=username, company=company).first() if user: password = user.password if password == body['password'].lower(): return jsonify(error=False, response=user.id), 200 else: return jsonify(error=True, message='The password is not correct'), 400 else: return jsonify(error=True, message='No user found with {} as email.'.format( body['email'])), 400 except Exception as e: log.error('Unexpected error in POST/user/login: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def delete(): try: body = request.json required_parameters = ['user_id', 'tag_id'] if not all(x in body for x in required_parameters): return jsonify( error=True, message='All request body parameters are required.'), 400 user = db_session().query(User).filter_by(id=body['user_id']).first() if not user: return jsonify(error=True, message='No user found with {} as id.'.format( body['user_id'])), 400 tag = db_session().query(Tag).filter_by(id=body['tag_id']).first() if not tag: return jsonify(error=True, message='No tag found with {} as id.'.format( body['tag_id'])), 400 user_tag = db_session().query(UserToTag).filter_by( user_id=body['user_id'], tag_id=body['tag_id']).first() if user_tag: db_session().delete(user_tag) db_session().commit() return jsonify(error=False, response='Deleted'), 200 else: return jsonify( error=True, message='No skill found for {} as user id, and {} as skill_id'. format(body['user_id'], body['tag_id'])), 400 except Exception as e: log.error('Unexpected error in POST/user/skills: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def playlist_get(participant_id): try: participant = db_session().query(Participant).filter_by( id=participant_id).first() if not participant: return jsonify( error=True, message='No participant found with {} as id.'.format( participant_id)), 400 if participant.route_id: playlist = songs.get_album([participant.music_genre]) else: genre_list = set() participants = db_session().query(Participant).filter_by( route_id=participant.route_id).all() for participant in participants: genre_list.add(participant.music_genre) playlist = songs.get_album(list(genre_list)) if playlist: return jsonify(error=False, response=playlist), 200 else: return jsonify(error=True, message='No playlist found.'), 400 except Exception as e: log.error('Unexpected error in GET/participant/playlist: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = [ 'title', 'description', 'destination', 'currency' ] if not all(x in body for x in required_parameters): return jsonify(error=True, message='{} are required parameters.'.format( required_parameters)), 400 trip = Trip(title=body['title'], description=body['description'], destination=body['destination'], currency=body['currency']) db_session().add(trip) db_session().commit() if trip.id: return jsonify(error=False, response=dict(trip_id=trip.id)), 200 else: return jsonify(error=True, message='Error while creating the new trip.'), 400 except Exception as e: log.error('Unexpected error in POST/trip: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(participant_id): try: participant = db_session().query(Participant).filter_by( id=participant_id).first() if participant: response = participant.serialize() if participant.route_id: car_mates = db_session().query(Participant).filter_by( route_id=participant.route_id).all() car_mates_name = [] for mate in car_mates: car_mates_name.append(mate.name) car = db_session().query(Car).filter( Car.participant_id == Participant.id).filter( Participant.route_id == participant.route_id).first() response['car'] = dict(passengers=car_mates_name, car_name=car.name) return jsonify(error=False, response=response), 200 else: return jsonify( error=True, message='No participant found with {} as id.'.format( participant_id)), 400 except Exception as e: log.error('Unexpected error in GET/participant: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = ['page_html', 'tlf', 'url'] if not all(x in body for x in required_parameters): return jsonify( error=True, message='All request body parameters are required.'), 400 soup = BeautifulSoup(body['page_html'], 'html.parser') images = list( set([ img.get('src') for img in soup.find_all('img') if img.get('src') ])) for img in images: data = computerVision.analyze(img) if data and (data['isAdultContent'] or data['isRacyContent']): print('Hi ha contingut inapropiat') message = 'Watch out, your kid has entered a webpage with inapropiate content. Link to the web {}'\ .format(body['url']) nexmo.send_sms('WatchMyKid', body['tlf'], message) break response = 'Ok' return jsonify(error=False, response=response), 200 except Exception as e: log.error('Unexpected error in POST/help: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = ['user_id', 'tag_name'] if not all(x in body for x in required_parameters): return jsonify( error=True, message='All request body parameters are required.'), 400 user = db_session().query(User).filter_by(id=body['user_id']).first() if not user: return jsonify(error=True, message='No user found with {} as id.'.format( body['user_id'])), 400 tag = db_session().query(Tag).filter_by(name=body['tag_name']).first() if not tag: return jsonify(error=True, message='No tag found with {} as name.'.format( body['tag_name'])), 400 user_tag = db_session().query(UserToTag).filter_by( user_id=body['user_id'], tag_id=tag.id).first() if not user_tag: user_tag = UserToTag(user_id=body['user_id'], tag_id=tag.id) db_session().add(user_tag) db_session().flush() db_session().commit() return jsonify(error=False, response=user_tag.serialize()), 200 except Exception as e: log.error('Unexpected error in POST/user/skills: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(prefix_tag): try: tags = db_session().query(Tag).filter( Tag.name.ilike(prefix_tag + '%')).limit(10).all() return jsonify(error=False, response=[tag.serialize() for tag in tags]), 200 except Exception as e: log.error('Unexpected error in GET/tag: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(car_id): try: car = db_session().query(Car).filter_by(id=car_id).first() if car: return jsonify(error=False, response=car.serialize()), 200 else: return jsonify(error=True, message='No car found with {} as id.'.format(car_id)), 400 except Exception as e: log.error('Unexpected error in GET/car: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def count(): try: user_query = db_session().query(User) user_query_count = user_query.statement.with_only_columns( [func.count()]).order_by(None) user_count = db_session().execute(user_query_count).scalar() return jsonify(error=False, response=user_count), 200 except Exception as e: log.error('Unexpected error in GET/user/count: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def update_routes(trip_id): try: distances = _compute_distances(trip_id) groups = _group_by_driver(distances, trip_id) groups = _sort_by_value(groups) _update_database(groups, trip_id) return groups except Exception as e: log.error('Unexpected error updating routes: {}'.format(e)) return None
def trip_get(trip_id): try: participants = db_session().query(Participant).filter_by( trip_id=trip_id).all() return jsonify( error=False, response=[participant.serialize() for participant in participants]), 200 except Exception as e: log.error('Unexpected error in GET/participant/trip: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def extract_tags_url(url): try: headers = {'X-RapidAPI-Key': os.environ['RAPID_API_KEY']} data = {'url': url} response = requests.get(IMAGGA_API_URL_TAGGING, params=data, headers=headers) response_json = response.json() return __extract_tags(response_json) except Exception as e: log.error('Error while extracting tags for a URL image.') log.exception(e) return None
def verify_get(location): try: # maps_response = maps.get_coordinates(location) maps_response = here.get_coordinates(location) if maps_response: return jsonify(error=False, response=maps_response), 200 else: return jsonify(error=True, message='Location not found.'), 400 except Exception as e: log.error('Unexpected error in GET/location/verify: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def random(): try: user = db_session().query(User).order_by(func.random()).first() if user: response = user.id return jsonify(error=False, response=response), 200 else: return jsonify(error=True, message='No users.'), 400 except Exception as e: log.error('Unexpected error in GET/user/random: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(user_id): try: user_skills = db_session().query(UserToTag).filter_by( user_id=user_id).all() return jsonify(error=False, response=[ user_skill.tag.serialize() for user_skill in user_skills ]), 200 except Exception as e: log.error('Unexpected error in GET/user/skills: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(trip_id): try: trip = db_session().query(Trip).filter_by(id=trip_id).first() if trip: return jsonify(error=False, response=trip.serialize()), 200 else: return jsonify( error=True, message='No trip found with {} as id.'.format(trip_id)), 400 except Exception as e: log.error('Unexpected error in GET/trip: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def extract_tags_base64(image_base64): try: image_id = __upload_image(image_base64) headers = {'X-RapidAPI-Key': os.environ['RAPID_API_KEY']} data = {'content': image_id} response = requests.get(IMAGGA_API_URL_TAGGING, params=data, headers=headers) response_json = response.json() return __extract_tags(response_json) except Exception as e: log.error('Error while extracting tags for a base64 image.') log.exception(e) return None
def get(phone_number): try: response = nexmo.send_message(phone_number) if response: return jsonify(error=False, message='Sent!'), 200 else: return jsonify( error=True, message='Error while sending the message to {}.'.format( phone_number)), 400 except Exception as e: log.error('Unexpected error in GET/share: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def search(prefix_user): try: prefix_user = str(prefix_user) users = db_session().query(User)\ .filter(cast(User.id, String).ilike(prefix_user + '%'))\ .order_by(User.id)\ .limit(10)\ .all() return jsonify(error=False, response=[user.serialize() for user in users]), 200 except Exception as e: log.error('Unexpected error in GET/user/search: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = ['trip_id', 'name', 'origin', 'music_genre'] if not all(x in body for x in required_parameters): return jsonify(error=True, message='{} are required parameters.'.format( required_parameters)), 400 trip = db_session().query(Trip).filter_by(id=body['trip_id']).first() if not trip: return jsonify(error=True, message='No trip found with {} as id'.format( body['trip_id'])), 400 participant = Participant(trip_id=body['trip_id'], name=body['name'], origin=body['origin'], music_genre=body['music_genre']) db_session().add(participant) db_session().flush() if participant.id: car_parameters = [ 'car_name', 'car_brand', 'car_model', 'car_available_seats' ] if all(x in body and body[x] for x in car_parameters): car = Car(participant_id=participant.id, name=body['car_name'], model=body['car_model'], brand=body['car_brand'], available_seats=body['car_available_seats']) db_session().add(car) db_session().flush() if not car.id: return jsonify( error=True, message='Error while creating the new car.'), 400 db_session().commit() update_routes(body['trip_id']) return jsonify(error=False, response=dict(participant_id=participant.id)), 200 else: return jsonify( error=True, message='Error while creating the new participant.'), 400 except Exception as e: log.error('Unexpected error in POST/participant: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = ['user_one', 'user_two'] if not all(x in body for x in required_parameters): return jsonify( error=True, message='All request body parameters are required.'), 400 if body['user_one'] == body['user_two']: return jsonify(error=True, message='Both user have to be different.'), 400 user_one = db_session().query(User).filter_by( id=body['user_one']).first() if not user_one: return jsonify(error=True, message='No user found with {} as id.'.format( body['user_one'])), 400 user_two = db_session().query(User).filter_by( id=body['user_two']).first() if not user_two: return jsonify(error=True, message='No user found with {} as id.'.format( body['user_two'])), 400 friend = db_session().query(Friend).filter_by( user_id_one=user_one.id, user_id_two=user_two.id).first() if not friend: friend_one = Friend(user_id_one=user_one.id, user_id_two=user_two.id) db_session().add(friend_one) db_session().flush() friend_two = Friend(user_id_one=user_two.id, user_id_two=user_one.id) db_session().add(friend_two) db_session().flush() db_session().commit() response = 'OK' else: response = 'Already created' return jsonify(error=False, response=response), 200 except Exception as e: log.error('Unexpected error in POST/friend: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(user_id): try: user = db_session().query(User).filter_by(id=user_id).first() if user: trip_list = db_session().query(Trip).filter_by( user_id=user_id).all() response = [trip.serialize() for trip in trip_list] return jsonify(error=False, response=response), 200 else: return jsonify( error=True, message='No user found with {} as id.'.format(user_id)), 400 except Exception as e: log.error('Unexpected error in GET/trip: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def post(): try: body = request.json required_parameters = ['page_html', 'user_id'] if not all(x in body for x in required_parameters): return jsonify(error=True, message='All request body parameters are required.'), 400 user = db_session().query(User).filter_by(id=body['user_id']).first() if not user: return jsonify(error=True, message='No user found with {} as id.'.format(body['user_id'])), 400 soup = BeautifulSoup(body['page_html'], 'html.parser') tag_list = list(set([a.text for a in soup.find_all('a', {'class': 'post-tag'})])) skills = {} company_mates = db_session().query(User).filter_by(company=user.company).all() for mate in company_mates: if mate.id != user.id: mate_skills = db_session().query(UserToTag).filter_by(user_id=mate.id).all() mate_skills = [skill.tag.name for skill in mate_skills] skills[mate.id] = [tag for tag in tag_list if tag in mate_skills] maximum = 0 maximum_mate = None maximum_list = None for mate, skill_list in skills.items(): if len(skill_list) > maximum: maximum = len(skill_list) maximum_mate = mate maximum_list = skill_list if maximum_mate and maximum_list: mate = db_session().query(User).filter_by(id=maximum_mate).first() if len(maximum_list) == 1: maximum_list_str = maximum_list[0] else: maximum_list_str = ', '.join(maximum_list[:-1]) maximum_list_str += ' and {}'.format(maximum_list[-1]) nexmo_message = 'Hey {}! Your friend {} is having some troubles with {}. Maybe you can give a hand!'\ .format(mate.full_name, user.full_name, maximum_list_str) nexmo.send_sms(NEXMO_SENDER, mate.phone_number, nexmo_message) response = dict(user=mate.serialize(), skills=maximum_list) else: response = dict(user=None, skills=[]) return jsonify(error=False, response=response), 200 except Exception as e: log.error('Unexpected error in POST/help: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def count_post(): request_body = request.json if not check.exist('ingredients_list', request_body): return response.build(error=True, error_message='No ingredients specified.') response_dict = {'total_calories': 0.0, 'ingredients': []} try: for ingredient in request_body['ingredients_list']: calories_count = nutritionix.get_ingredient_calories(ingredient) response_dict['total_calories'] += calories_count response_dict['ingredients'].append({'calories': calories_count, 'ingredient': ingredient}) return response.build(error=False, response=response_dict) except Exception as e: log.error('Error while counting calories.') log.exception(e) return response.build(error=True, error_message='Unexpected error.')
def get_coordinates(location): payload = { 'app_id': HERE_APP_ID, 'app_code': HERE_APP_CODE, 'searchtext': location } response = requests.get(HERE_GEO_CODER_URL, params=payload) response_json = response.json() try: latitude = response_json['Response']['View'][0]['Result'][0][ 'Location']['DisplayPosition']['Latitude'] longitude = response_json['Response']['View'][0]['Result'][0][ 'Location']['DisplayPosition']['Longitude'] return dict(lat=latitude, lng=longitude) except Exception as e: log.error( 'Error getting latitude and longitude from Here response: {}'. format(e)) return None
def get(user_id): try: user = db_session().query(User).filter_by(id=user_id).first() if user: friend_list = db_session().query(Friend).filter_by( user_id_one=user_id).all() friend_list = [ friend.user_two.serialize() for friend in friend_list ] response = sorted(friend_list, key=lambda k: k['points'], reverse=True) return jsonify(error=False, response=response), 200 else: return jsonify( error=True, message='No user found with {} as id.'.format(user_id)), 400 except Exception as e: log.error('Unexpected error in GET/friend: {}'.format(e)) return jsonify(error=True, message='Unexpected error.'), 400
def get(user_id): try: week_date = datetime.datetime.today() - datetime.timedelta(days=7) reports = db_session().query(Report).filter(and_(Report.time >= week_date, Report.username == user_id)).all() response_dict = {} while week_date.date() < datetime.datetime.now().date(): week_date = week_date + datetime.timedelta(days=1) response_dict[week_date.strftime("%Y-%m-%d")] = 0.0 for report in reports: response_dict[report.time.strftime("%Y-%m-%d")] += float(report.calories) response_list = [] for key, value in response_dict.items(): response_list.append({'date': key, 'calories': int(value)}) return response.build(error=False, response=response_list) except Exception as e: log.error('Exception while getting data for the dashboard.') log.exception(e) return response.build(error=True, error_message='Unexpected error.')