def removeFollower(username): username_to_remove = request.data['follow'] with queries.transaction(): if not queries.user_exists(user_name=username): raise exceptions.NotFound("The current user does not exist.") if not queries.user_exists(user_name=username_to_remove): raise exceptions.NotFound("The user you are trying to unfollow does not exist.") if queries.remove_follower(user_name=username, followed_name=username_to_remove): return { "unfollowed": request.data['follow'] }, status.HTTP_200_OK else: raise exceptions.NotFound("Could not unfollow: relationship does not exist.")
def addFollower(username): username_to_follow = request.data['follow'] with queries.transaction(): if not queries.user_exists(user_name=username): raise exceptions.NotFound("The current user does not exist.") if not queries.user_exists(user_name=username_to_follow): raise exceptions.NotFound("The user you are trying to follow does not exist.") try: queries.add_follower(user_name=username, followed_name=username_to_follow) except Exception as e: return {'message': 'You are already following this user.'}, status.HTTP_409_CONFLICT return { "followed": request.data['follow'] }, status.HTTP_201_CREATED
def recent_posts_sub(sub, number_of_posts): get_recent_posts_sub = queries.get_recent_posts_sub( sub=sub, number_of_posts=number_of_posts) if (get_recent_posts_sub): return list(get_recent_posts_sub) else: raise exceptions.NotFound()
def filterTrackByID(trackID): shardKey = trackID.int % 3 if request.method == "GET": if shardKey == 0: trackByID = trackQueries.track_by_id(trackID=trackID) elif shardKey == 1: trackByID = trackQueries2.track_by_id(trackID=trackID) elif shardKey == 2: trackByID = trackQueries.track_by_id(trackID=trackID) else: raise exceptions.ParseError() if trackByID is None: raise exceptions.NotFound() return trackByID elif request.method == "DELETE": try: if shardKey == 0: affected = trackQueries.delete_by_id(trackID=trackID) elif shardKey == 1: affected = trackQueries2.delete_by_id(trackID=trackID) elif shardKey == 2: affected = trackQueries3.delete_by_id(trackID=trackID) else: raise exceptions.ParseError() if affected == 0: return {'Error': "TRACK NOT FOUND"}, status.HTTP_404_NOT_FOUND else: return { 'DELETE REQUEST ACCEPTED': str(trackID) }, status.HTTP_202_ACCEPTED except Exception as e: return {'Error': str(e)}, status.HTTP_409_CONFLICT
def delete(id): delete = queries.delete_user_by_id(id=id) if (delete.rowcount == 1): # if row is deleted return 204 without content return '', 204 else: raise exceptions.NotFound()
def create_tracks_Query(args): q_args = [] query = '' title = args.get('title') artist = args.get('artist') loc = args.get('link') len = args.get('length') art = args.get('artwork') if title: query += " title=? AND" q_args.append(title) if artist: query += " artist=? AND" q_args.append(artist) if loc: query += " link=? AND" q_args.append(loc) if len: query += " length=? AND" q_args.append(len) if art: query += " artwork=? AND" q_args.append(art) if not (title or len or artist or art or loc): raise exceptions.NotFound() query = query[:-4] return (query, q_args)
def delete_track(track): if 'id' in track: track = {"TrackId": track['id']} try: shard_key = track['TrackId'] % 3 if shard_key == 0: queries1.delist_track_from_playlists(**track) track = queries1.delete_track_by_id(**track) elif shard_key == 1: queries2.delist_track_from_playlists(**track) track = queries2.delete_track_by_id(**track) elif shard_key == 2: queries3.delist_track_from_playlists(**track) track = queries3.delete_track_by_id(**track) except Exception as e: return {'error': str(e)}, status.HTTP_409_CONFLICT if track: return {"info": "Successfully deleted"}, status.HTTP_200_OK else: raise exceptions.NotFound() return { 'error': "Did not provide an id for track to be deleted" }, status.HTTP_400_BAD_REQUEST
def user_update(key): if key not in users: raise exceptions.NotFound() user = str(request.data.get('name', '')) users[key] = user return user
def events_detail(key): """ Retrieve, update or delete events instances. """ event = Event.query.get(key) if request.method == 'PUT': data_list = str(request.data.get('text', '')).split() calendar = data_list[0] name = data_list[1] date = data_list[2] if calendar != '' and name != '' and date != '': event.calendar = calendar event.name = name event.date = datetime.date.fromisoformat(date) db.session.add(event) db.session.commit() return event.get_JSON(), status.HTTP_201_CREATED else: return { "error": "calendar, date, and name required" }, status.HTTP_400_BAD_REQUEST return date_repr(key) elif request.method == 'DELETE': db.session.delete(event) db.session.commit() return '', status.HTTP_204_NO_CONTENT # request.method == 'GET' if not event: raise exceptions.NotFound() return event.get_JSON()
def reset_password(): """Reset user Password endpoint takes in a password and resets the password""" password = request.data.get('password') access_token = authentication_request() if access_token: # Attempt to decode the token and get the User ID user_id = Users.decode_token(access_token) if not isinstance(user_id, str): user = Users.query.filter_by(id=user_id).first() try: if not user: raise exceptions.NotFound() valid_password = check_password_validation(password) user.password = Users.hash_password(valid_password) user.save() # db.session.commit() return { "message": "you have succesfuly reset your password" }, status.HTTP_200_OK except Exception as error: return {"message": str(error)}, status.HTTP_200_OK else: return {"message": user_id}, status.HTTP_401_UNAUTHORIZED return { "message": "Provide a valid authentication token" }, status.HTTP_403_FORBIDDEN
def retrieve_user_profile(UserId): user_profile = queries.user_by_id(UserId=UserId) if user_profile: return user_profile, status.HTTP_200_OK, { "Content-Type": "application/json" } else: raise exceptions.NotFound()
def filterPlaylists(queryParams): playID = queryParams.get("playID") playTitle = queryParams.get("playTitle") userName = queryParams.get("userName") query = "SELECT P.playID, P.playTitle, P.playDesc, P.playListOfTracks, U.userUserName FROM playlists as P, users as U WHERE P.playUserID = U.userID AND" to_filter = [] if playID: query += ' P.playID=? AND' to_filter.append(playID) if playTitle: query += ' P.playTitle=? AND' to_filter.append(playTitle) if userName: query += " U.userUserName = ? AND" to_filter.append(userName) if not (playID or playTitle or userName): raise exceptions.NotFound() query = query[:-4] + ';' results = plQueries._engine.execute(query, to_filter).fetchall() results = list(map(dict, results)) return results
def allPlaylists(): allPlaylists = plQueries.all_playlists() allPlaylists = list(allPlaylists) if len(allPlaylists) is 0: raise exceptions.NotFound() else: return allPlaylists
def get_public_timeline(): public = queries.public_timeline() if public: #app.logger.debug(type(public)) return list(public) else: raise exceptions.NotFound()
def item_detail(key): """ Retrieve instances """ if key not in g.items: raise exceptions.NotFound() return item_repr(key)
def get_track(id): temp = queries.search_by_id(id=id) #return queries.search_by_id(id=id) if temp: return temp, status.HTTP_200_OK else: raise exceptions.NotFound()
def recent_posts(number_of_posts): get_recent_posts_all = queries.get_recent_posts_all( number_of_posts=number_of_posts) if (get_recent_posts_all): return list(get_recent_posts_all) else: raise exceptions.NotFound()
def post_by_community(Community): n = request.args.get('n',3) post = queries.post_by_community(Community=Community,n=n) if post: return list(post) else: raise exceptions.NotFound()
def block_detail(key): """ Retrieve block instances """ if key not in blocks: raise exceptions.NotFound() return block_digest(key)
def filter_users(query_parameters): id = query_parameters.get('id') username = query_parameters.get('username') hashed_password = query_parameters.get('hashed_password') query = "SELECT * FROM users WHERE" to_filter = [] if username and password: return authenticate_user(username,password) if id: query += ' id=? AND' to_filter.append(id) if username: query += ' username=? AND' to_filter.append(username) if hashed_password: query += ' hashed_password=? AND' to_filter.append(hashed_password) if not (id or username or hashed_password): raise exceptions.NotFound() query = query[:-4] + ';' results = queries._engine.execute(query, to_filter).fetchall() return list(map(dict, results))
def changePassword(): authData = request.data required_fields = ['username', 'new_password'] # Check if required fields exists if not all([field in authData for field in required_fields]): raise exceptions.ParseError() try: user = session.execute( """ SELECT * FROM users where username=%s ALLOW FILTERING """, (authData['username'],) ) if user.one(): session.execute( """ UPDATE users SET password=%s WHERE username=%s """, (generate_password_hash(authData['new_password']), authData['username']) ) print(user) return { 'success': 'password updated' } else: raise exceptions.NotFound() except Exception as e: return { 'error': str(e) }, 401
def filter_tracks(query_parameters): id = query_parameters.get('id') title = query_parameters.get('title') album = query_parameters.get('album') artist = query_parameters.get('artist') #duration = query_parameters.get('duration') #url = query_parameters.get('url') #arturl = query_parameters.get('arturl') query = "SELECT * FROM tracks WHERE" to_filter = [] if id: query += ' id=? AND' to_filter.append(id) if title: query += ' title=? AND' to_filter.append(title) if album: query += ' album=? AND' to_filter.append(album) if not (id or title or album or artist): raise exceptions.NotFound() query = query[:-4] + ';' results = queries._engine.execute(query, to_filter).fetchall() #one = results['title'] #return results #return list(results) return list(map(dict, results))
def filterTracks(queryParams): trackTitle = queryParams.get("trackTitle") trackAlbum = queryParams.get("trackAlbum") trackArtist = queryParams.get("trackArtist") query = "SELECT * FROM tracks WHERE" to_filter = [] if trackTitle: query += ' trackTitle=? AND' to_filter.append(trackTitle) if trackAlbum: query += ' trackAlbum=? AND' to_filter.append(trackAlbum) if trackArtist: query += ' trackArtist=? AND' to_filter.append(trackArtist) if not (trackTitle or trackAlbum or trackArtist): raise exceptions.NotFound() query = query[:-4] + ';' results1 = trackQueries._engine.execute(query, to_filter).fetchall() results2 = trackQueries2._engine.execute(query, to_filter).fetchall() results3 = trackQueries3._engine.execute(query, to_filter).fetchall() return list(map(dict, results1)) + list(map(dict, results2)) + list( map(dict, results3))
def filter_books(query_parameters): id = query_parameters.get('id') published = query_parameters.get('published') author = query_parameters.get('author') query = "SELECT * FROM books WHERE" to_filter = [] if id: query += ' id=? AND' to_filter.append(id) if published: query += ' published=? AND' to_filter.append(published) if author: query += ' author=? AND' to_filter.append(author) if not (id or published or author): raise exceptions.NotFound() query = query[:-4] + ';' results = queries._engine.execute(query, to_filter).fetchall() return list(map(dict, results))
def data_set(key): """Data set content. Resource containing data set content. If the 'q' query parameter is specified a list of up to 10 data set items that 'fuzzily' match the query parameter are returned. This means a query string can be a misspelling; suggester will use Bayesian probabilities to have a good guess at candidate matches. If no 'q' query parameter is specified a all data set content is returned (paginated). """ all_data_sets = registry.get_data_sets() if key not in all_data_sets: raise exceptions.NotFound() source = all_data_sets[key]['source'] query = request.args.get('q') page_size = int(request.args.get('size', PAGE_SIZE)) if query: matches = _get_suggestions(source, query, page_size) return dict(previous=None, next=None, start=None, matches=matches, items=None, count=len(matches)) else: start = int(request.args.get('start', 1), ) url = request.host_url.rstrip('/') + url_for('data_set', key=key) return _paginate(registry.get_data_set_content(source), url, start)
def _paginate(data, url, start, page_size): """Paginate data set content. :param (dict) data: The data set content. :param (str) url: URL to resource used to be used in perv/next properties. :param (int) start: Page position. :returns (dict): Paginated resource content. """ qty = len(data) if start > qty or start < 1: raise exceptions.NotFound() response = dict(start=start) if start == 1: response['previous'] = None else: previous_pos = max(1, start - page_size) response['previous'] = url + f'?start={previous_pos}' next_pos = min(qty, start + page_size) if next_pos >= qty: response['next'] = None else: response['next'] = url + f'?start={next_pos}' start_idx = start - 1 response['matches'] = None page = data[start_idx:start_idx + page_size] response['items'] = page response['count'] = len(page) return response
def epic_detail(epic): """ Retrieve, update or delete note instances. """ epic_detail = streamer.epic_details.get(epic) if not epic or not epic_detail: raise exceptions.NotFound() return epic_detail
def get_building(id): curs = db.get_cursor() curs.execute('SELECT id, name FROM buildings WHERE id = %s', (id)) if curs.rowcount < 1: raise exceptions.NotFound() return curs.fetchone().copy()
def _get_watchlist(username, watchlist_name): """ Attempt to fetch a specific watchlist from a user """ if not current_app.mongo.db.users.find_one({"username": username}): raise exceptions.NotFound(f"User {username} does not exist") record = current_app.mongo.db.users.find_one({ "username": username, "watchlists.watchlist_name": watchlist_name }) if not record: raise exceptions.NotFound(f"Watchlist {watchlist_name} not found") return record["watchlists"][0]
def get_user(username): if username is None: raise exceptions.ParseError("`username` not provided!") user_data = current_app.mongo.db.users.find_one({"username": username}) if user_data is None: raise exceptions.NotFound(f"User {username} not found in users table") return jsonify(user_data)