def get_projects(page: int, category_name: str): from .utils import load_projects_data # Get projects from database. if not category_name: category_name = "science" try: category = Category.query.filter_by(name=category_name).first() projects_query = (Project.query.filter_by( category=category).order_by(Project.created.desc()).paginate( page, current_app.config["PROJECTS_PER_PAGE"], False)) projects_data = load_projects_data(projects_query.items) resp = message(True, "Projects data sent.") resp["page"] = load_page_data(projects_query) resp["projects"] = projects_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def login(data): # Assign vars email = data["email"] password = data["password"] try: # Fetch user data user = User.query.filter_by(email=email).first() if not (user): return err_resp( "The email you have entered does not match any account.", "email_404", 404, ) elif user and user.verify_password(password): user_info = user_schema.dump(user) access_token = create_access_token(identity=user.id) resp = message(True, "Successfully logged in.") resp["access_token"] = access_token resp["user"] = user_info return resp, 200 return err_resp("Failed to log in, password may be incorrect.", "password_invalid", 401) except Exception as error: current_app.logger.error(error) return internal_err_resp()
class PodcastService: @staticmethod def get(pdcast_id): if not (song := Podcast.query.get(pdcast_id)): return err_resp("Podcast file not found", "audio_404", 404) try: podcast_data = PodcastService.load_data(song) resp = message(True, "Podcast data sent") resp["podcast"] = podcast_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def register(data): # Assign vars ## Required values email = data["email"] username = data["username"] password = data["password"] ## Optional data_name = data.get("name") # Check if the email is taken if User.query.filter_by(email=email).first() is not None: return err_resp("Email is already being used.", "email_taken", 403) # Check if the username is taken if User.query.filter_by(username=username).first() is not None: return err_resp("Username is already taken.", "username_taken", 403) try: new_user = User( email=email, username=username, name=data_name, password=password, joined_date=datetime.utcnow(), ) db.session.add(new_user) db.session.flush() # Load the new user's info user_info = user_schema.dump(new_user) # Commit changes to DB db.session.commit() # Create an access token access_token = create_access_token(identity=new_user.id) resp = message(True, "User has been registered.") resp["access_token"] = access_token resp["user"] = user_info return resp, 201 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def get_all_data(): """ Get all playlists data """ playlists = Playlist.query.all() try: playlist_data = playlists_schema.dump(playlists) resp = message(True, "Playlists data sent") resp["playlists"] = playlist_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class SongService: @staticmethod def get(song_id): if not (song := Song.query.get(song_id)): return err_resp("Song not found", "audio_404", 404) try: song_data = SongService.load_data(song) resp = message(True, "Song data sent") resp["song"] = song_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def __add_user(data, is_superuser=False): # Required values email = data["email"] password = data["password"] date_joined = data["date_joined"] if type(date_joined) is str: date_joined = dateutil.parser.parse(date_joined) date_joined = date_joined.astimezone(timezone('UTC')) # Optional data_first_name = data.get("first_name") data_last_name = data.get("last_name") data_is_active = data.get("is_active") data_is_staff = data.get("is_staff") # Check if the email is taken if User.objects(email=email).first() is not None: return validation_error( False, {"email": ["این ایمیل قبلا ثبت شده است."]}), 422 try: new_user = User( first_name=data_first_name, last_name=data_last_name, date_joined=date_joined, email=email, is_active=data_is_active, is_staff=data_is_staff, is_superuser=is_superuser, ) new_user.set_password_hash(password) new_user.save() # Load the new user's info user_info = user_schema.dump(new_user) resp = message(True, "کاربر با موفقیت ایجاد شد.") resp["user"] = user_info return resp, 201 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def get_user_data(username): """ Get user data by username """ user = User.query.filter_by(username=username).first() if not (user): return err_resp("User not found!", "user_404", 404) from .utils import load_data try: user_data = load_data(user) resp = message(True, "User data sent") resp["user"] = user_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def upload_data_from_csv(file): """ Receives data to upload to airport table """ try: file_data = serialize_file_data(file) # Add airports registry for single_airport in file_data: airport = Airport(**single_airport) db.session.add(airport) db.session.commit() resp = message(True, "Airports data uploaded with success") return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def create_airport(data): """ Create a new airport registry """ from .utils import load_data try: airport = Airport(**data) db.session.add(airport) db.session.commit() resp = message(True, f"New airport saved.") resp["data"] = load_data(airport); return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def get_posts(page: int): from .utils import load_posts_data # Get posts from database. try: posts_query = Post.query.order_by(Post.created.desc()).paginate( page, current_app.config["POSTS_PER_PAGE"], False) posts_data = load_posts_data(posts_query.items) resp = message(True, "Posts data sent.") resp["page"] = load_page_data(posts_query) resp["posts"] = posts_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class AirportService: @staticmethod def get_airport_data(id): """ Get airport data by id """ if not (airport := Airport.query.filter_by(id=id).first()): return err_resp("Airport not found!", "airport_404", 404) from .utils import load_data try: airport_data = load_data(airport) resp = message(True, f"'{airport.name}' airport data") resp["data"] = airport_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class UserService: @staticmethod def get_user_data(id): """ Get user data by id """ if not (user := User.query.filter_by(id=id).first()): return err_resp("User not found!", "user_404", 404) from .utils import load_data try: user_data = load_data(user) resp = message(True, "User data sent") resp["user"] = user_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class TrackService: @staticmethod def get_track_data(track_id): """ Get track data by track_id """ if not (track := Track.query.filter_by(id=track_id).first()): return err_resp("Track not found!", "track_404", 404) from .utils import load_data try: track_data = load_data(track) resp = message(True, "Track data sent") resp["track"] = track_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def update_data(data, user): if not data: return message(True, "Nothing to update."), 204 try: from app import db for key, value in data.items(): setattr(user, key, value) # Commit changes to db. db.session.commit() return message(True, "User data updated."), 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class PlaylistService: @staticmethod def get_playlist_data(playlist_id): """ Get playlist data by playlist_id """ if not (playlist := Playlist.query.filter_by(id=playlist_id).first()): return err_resp("Playlist not found!", "playlist_404", 404) from .utils import load_data try: playlist_data = load_data(playlist) resp = message(True, "Playlist data sent") resp["playlist"] = playlist_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class PostService: @staticmethod def get_data(public_id): """ Get Post data by its public id """ if not (post := Post.query.filter_by(public_id=public_id).first()): return err_resp("Post not found!", "post_404", 404) from .utils import load_data try: post_data = load_data(post) resp = message(True, "Post data succcessfully sent.") resp["post"] = post_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
class ProjectService: @staticmethod def get_data(public_id): """ Get Project data by its public id """ if not (project := Project.query.filter_by(public_id=public_id).first()): return err_resp("Project not found!", "project_404", 404) try: from .utils import load_data project_data = load_data(project) resp = message(True, "Project data sent") resp["project"] = project_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def get_all_user_data(): """ Get user data by username """ users = User.query.all() if not (users): return err_resp("User not found!", "user_404", 404) from .utils import load_data try: user_data_list = [] for user in users: user_data = load_data(user) if user_data: user_data_list.append(user_data) resp = message(True, "User data sent") resp["users"] = user_data_list return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp()
from .utils import load_data try: airport.deleted = True # logic deletion db.session.commit() airport_data = load_data(airport) resp = message(True, f"'{airport.name}' airport deleted") resp["data"] = airport_data return resp, 200 except Exception as error: current_app.logger.error(error) return internal_err_resp() @staticmethod def update_airport(id, data): """Update a specific airport by id""" if not (airport := Airport.query.filter_by(id=id).first()): return err_resp("Airport not found!", "airport_404", 404) from .utils import load_data try: for key in data.keys(): if data.get(key, False): # Existing key in airport object setattr(airport, key, data[key])
@staticmethod def create(data): if errors := SongSchema().validate(data=data): return validation_error(False, errors), 400 try: new_song = Song(name=data["name"], duration=data["duration"]) db.session.add(new_song) db.session.commit() resp = message(True, "Song has been created.") resp["song"] = SongService.load_data(new_song) return resp, 200 except Exception as reason: current_app.logger.exception( f"an error occur while creating Audiobook: {reason}", reason) return internal_err_resp(reason.__str__()) @staticmethod def delete(audio_id): msg = message(True, "") if not (audio_book := Song.query.get(audio_id)): return msg db.session.delete(audio_book) db.session.commit() return msg @staticmethod def update(audio_id, file_path, uploaded_time): if not (song := Song.query.get(audio_id)): return err_resp("Song not found", "song_404", 404) if not file_path.exists() and file_path.is_file():
@staticmethod def create(data): if errors := PodcastSchema().validate(data=data): return validation_error(False, errors), 400 try: new_song = Podcast(name=data["name"], host=data["host"], participants=data["participants"], duration=data["duration"]) db.session.add(new_song) db.session.commit() resp = message(True, "Podcast has been created.") resp["podcast"] = PodcastService.load_data(new_song) return resp, 200 except Exception as reason: current_app.logger.exception(f"an error occur while creating Podcast: {reason}", reason) return internal_err_resp() @staticmethod def delete(audio_id): msg = message(True, "") if not (audio_book := Podcast.query.get(audio_id)): return msg db.session.delete(audio_book) db.session.commit() return msg @staticmethod def update(audio_id, file_path, uploaded_time): if not (podcast := Podcast.query.get(audio_id)): return err_resp("Podcast not found", "podcast_404", 404) if not file_path.exists() and file_path.is_file():