def upcomingEpisodes(): """ This function is called when the user is trying to go on his upcoming episode page We provide the different series lists divided in 3 : * The series the user is watching but is not up to date (ex : the user last saw the episode 3 of the first season while the series last episode is S4E3 > list_series_last_episode * The user is up to date with this serie and we're expecting an episode for this show > list_series_up_to_date * The user is up-to-date with the serie but we're not expecting any next episode > list_series_finished We also change the notifications to 0 :return:render_template('upcoming_episode.html') """ l_utd, l_nutd, l_fin = current_user.check_upcoming_episodes() # We fill the list with all the series info using the Api get_serie method list_up_to_date, list_not_up_to_date, list_finished = [], [], [] for s_id in l_utd: app.logger.info(msg=f'Serie {s_id} added to up to date shows') list_up_to_date.append(Api.get_media(type_media='tv', id_media=s_id)) for s_id in l_nutd: app.logger.info(msg=f'Serie {s_id} added to not up to date shows') list_not_up_to_date.append(Api.get_media(type_media='tv', id_media=s_id)) for s_id in l_fin: app.logger.info(msg=f'Serie {s_id} added to finished shows') list_finished.append(Api.get_media(type_media='tv', id_media=s_id)) current_user.notifications = bytes(0) db.session.commit() return render_template('upcoming_episodes.html', title='Upcoming Episodes', list_next_episode=list_up_to_date, list_last_episode=list_not_up_to_date, list_finished=list_finished, tv_genres=tv_genres, movie_genres=movie_genres, user=current_user)
class AppTestCase(TestCase): def setUp(self): self.api = Api() @mock.patch('requests.get', side_effect=mocked_requests_get_one) def test__get_currency(self, mockget): curr = 'PLN/AED' json_data = self.api.get_currency(curr) assert json_data == success_one @mock.patch('requests.get', side_effect=ValueError) def test__get_currency_err(self, mockget): curr = 'PLN/AED' json_data = self.api.get_currency(curr) assert json_data == success_err @mock.patch('app.api.Api.get_currency', return_value=success_all) def test__get_all_currencies(self, mockget): result = self.api.get_all_currencies() assert result['EUR'] == success_all['currency'] def test__get_codes(self): assert len(self.api.read_codes()) == 51
def __init__(self): self.g = Api() # Vai buscar a class API do ficheiro api.py # Janela Principal self.main_window = QMainWindow() self.main_window_form = Ui_MainWindow() self.main_window_form.setupUi(self.main_window) self.main_window.show() # Janela Adicionar self.main_window2 = QMainWindow() self.main_window_form2 = Ui_MainWindow2() self.main_window_form2.setup(self.main_window2) # Janela Modificar self.main_window4 = QMainWindow() self.main_window_form4 = Ui_MainWindow4() self.main_window_form4.setup4(self.main_window4) # Janela Pesquisar self.main_window5 = QMainWindow() self.main_window_form5 = Ui_MainWindow5() self.main_window_form5.setup5(self.main_window5) # Janela Mostrar Imagem self.main_window6 = QMainWindow() self.main_window_form6 = Ui_MainWindow6() self.main_window_form6.setup6(self.main_window6) self.bindings( ) #chamar a funçao bindings a class , para que os butoes consigam "correr" self.database( ) #chamar a funcao database, para que mostra a base de dados no inicio
def create_app(): app_init = Flask(__name__) app_init.config.from_object(runtime_config()) configure_uploads(app_init, (CSV_UPLOADER, )) api_1_0_blueprint = Blueprint('api_1_0', __name__) api_1_0 = Api(api_1_0_blueprint) api_1_0.add_resource(UploadCsv, '/files', endpoint='upload_file') app_init.register_blueprint(api_1_0_blueprint, url_prefix='/api') return app_init
def del_user(): user_id = request.args.get('user_id') if not user_id: abort(404) user = User.query.get(user_id) try: db.session.delete(user) db.session.commit() return Api.success() except: db.session.rollback() return Api.unauth_error(msg='无法删除此用户')
def post_media_grade(id_media, type_media): """ Fonction appelee pour envoyer a l'API la note donnee par l'utilisateur au film ou a la serie :param id_media: int. Id du média :param type_media: string. Type du média : 'tv' ou 'movie" :return: """ grade = current_user.current_grade session = current_user.session_id current_user.grade(id_media=id_media, media=type_media, grade=grade) Api.rate(id=id_media, grade=grade, media=type_media, session=session, user=current_user) app.logger.info(msg=f'The user posted the grade {int(grade)} for the {type_media} {id_media}') return media(type_media=type_media, id=id_media)
def home(): """ Cette fonction permet de retourner la home page de notre site qui indique les dernieres sorties de series et films. On passe egalement les genres de series et de films en parametres pour la sidebar :return:void """ suggestions_serie = Api.get_popular('serie', 1) suggestions_movie = Api.get_popular('movie', 1) selection_serie, selection_movie = [], [] for i in range(12): selection_serie.append(suggestions_serie[i]) selection_movie.append(suggestions_movie[i]) return render_template('home.html', title='Home', suggestions_serie=selection_serie, suggestions_movie=selection_movie, nombre_series=12, tv_genres=tv_genres, movie_genres=movie_genres)
def add_user(): if request.method == "GET": return render_template('cms_addcmsuser.html') else: form = AddUserForm(request.form) if form.validate(): login_name = form.login_name.data name = form.name.data user = User(login_name=login_name,name=name) user.password = '******' db.session.add(user) db.session.commit() return Api.success() else: return Api.params_error(form.get_error)
def get_episode(self): ''' Méthode utilisée pour recupérer l'épisode actuel depuis l'API :return: Un objet épisode correspondant à l'épisode actuel ''' return Api.get_episode(self.id, self.get_current_season(), self.get_current_episode())
def select_episode(id, season, episode): """ Fonction utilisee pour afficher l'episode {episode} de la saison {season} dans la page serie : son image et son resume :param id: int. id de la série :param season: numéro de la saison :param episode: numéro de l'épisode :return: """ serie = Api.get_media(type_media='tv', id_media=id) similar = Api.get_similar(id, 'tv') serie.selected_episode = 'S' + str(season) + 'E' + str(episode) episode = serie.get_episode app.logger.info(msg=f'Selected Episode : Serie = {id}, Season = {season}, episode = {episode.num_episode}') return render_template('serie.html', media=serie, user=current_user, episode=episode, season=episode.num_season, type_media='tv', similar=similar, tv_genres=tv_genres, movie_genres=movie_genres)
def reset_pwd(): if request.method == 'GET': return render_template('cms_resetpwd.html') else: form = ResetPwdForm(request.form) if form.validate(): old_pwd = form.old_pwd.data new_pwd = form.new_pwd.data user = g.cms_user if user.check_pwd(old_pwd): user.password = new_pwd db.session.commit() return Api.success() else: return Api.params_error(msg='旧密码错误!') else: return Api.params_error(msg=form.get_error)
def edit_user(): user_id = request.args.get('user_id') if request.method == 'GET': if not user_id: abort(404) user = User.query.get(user_id) context = {'user':user} return render_template('/cms_editcmsuser.html',**context) else: permission = request.form.get('permission') if permission: user = User.query.get(user_id) user.permission = '管理员' if permission =='1' else '操作员' db.session.commit() return Api.success() else: return Api.params_error(msg='没有相应的权限')
def login(): """ Cette route correspond a la page de login On verifie que l'utilisateur a bien rentré les bonnes informations de connexion sinon on refuse son authentification Puis, si les informations sont bonnes, on recalcule l'etat des series de l'utilisateur (utd, nutd et fin) pour pouvoir afficher les bonnes notifications (que l'on rend donc actives) De plus, on lui cree un nouvel identifiant de session pour pouvoir poster sur l'API Enfin, on le redirige vers la page qu'il souhaitait voir (home si il n'en a pas) :return: """ app.logger.info(msg='The user is logging in') # Si l'utilisateur est deja connecte, il ne peut acceder a cette page if current_user.is_authenticated: return redirect(url_for('home')) # On utilise LoginForm du module forms.py form = LoginForm() # Si le formulaire n'est pas rempli, on demande de le reremplir if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() # Si aucun utilisateur n'a ce nom on flash un message indiquant qu'il y a eu une erreur dans le nom if user is None: app.logger.info(msg='Invalid Username !') flash("Invalid Username !") return render_template('login.html', title='Sign In', form=form, src=logo_source) # Si le mot de passe n'est pas bon, on l'indique egalement a l'utilisateur elif not user.check_password(form.password.data): app.logger.info(msg='Invalid Password !') flash("Invalid Password !") return render_template('login.html', title='Sign In', form=form, src=logo_source) # Sinon, on connecte l'utilisateur et on met a jour ses informations else: login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') app.logger.info(msg='Successful Login !') # Si il n'a pas de pages en memoire, on le redirige vers home if not next_page or url_parse(next_page).netloc != '': next_page = url_for('home') # On lui ajoute une session current_user.session_id = Api.new_session() db.session.commit() # On rend ses notifications actives et on met a jour le statut de ses series current_user.notifications = bytes(1) current_user.update_all_upcoming_episodes() db.session.commit() return redirect(next_page) return render_template('login.html', title='Sign In', form=form, src=logo_source)
def login(): if request.method == 'GET': return render_template('login.html') else: form = LoginForm(request.form) if form.validate(): login_name = form.login_name.data password = form.password.data remember = form.remember.data user = User.query.filter_by(login_name=login_name).first() if user and user.check_pwd(password): session[current_app.config['USER_ID']] = user.id if remember: session.permanent = True return Api.success() else: return Api.params_error(msg='用户名或密码错误,请重新输入') else: return Api.params_error(msg=form.get_error)
def view_episode(self, episode, season, serie): """ Cette methode permet de modifier le dernier episode vu par un utilisateur On remplace le dernier episode vu par l'utilisateur pour la serie d'ID "serie" par l'episode "episode" de la saison "season". On va donc remplacer le code de l'episode et de la saison dans UserMedia par les bons codes Cette methode met egalement le statut de la serie a jour (utd/fin/nutd) :param episode: (int) numero de l'episode a marquer comme vu :param season: (int) numero de la saison de cet episode :param serie: (int) identifiant de la serie :return: void """ # On recupere la serie des series de l'utilisateur show = self.user_media.filter_by(media='tv', media_id=int(serie)).first() # Si la serie n'est pas dans les series de l'utilisateur, on ne fait rien if show: # On appelle l'API pour obtenir les informations de la serie s = Api.get_media(type_media='tv', id_media=str(serie)) # On update la saison et l'episode de l'utilisateur show.season_id = season show.episode_id = episode # On recupere la saison et le numero du dernier episode sorti latest_season, latest_ep = s.latest['season_number'], s.latest[ 'episode_number'] status = '' # Si le dernier episode et lepisode vu par l'utilisateur sont les memes, on regarde si il y a un # episode qui doit sortir if not self.is_after( season=latest_season, episode=latest_ep, serie=s.id): # Si il n'y a pas d'episode a venir, la serie est terminee if s.date == '': status = 'fin' else: # Sinon on change le statut de la serie a a jour (utd) status = 'utd' else: # Sinon la serie n'est pas a jour car il reste des episodes a voir, on change le statut en nutd status = 'nutd' show.state_serie = status # On met a jour les notifications self.notifications = bytes(1) db.session.commit()
def start(self): try: api=Api(self._name,self._version,self._broker_host,self._broker_port,self._broker_username,self._broker_password) self.log.print("Listening to all APIs","OK") sub=Subscriber(api,self._name,self._version,self._broker_host,self._broker_port,self._broker_username,self._broker_password,self._lock) sub_thread = Threads(1, "Subscriber Thread",self._lock,sub) sub_thread.start() sub_thread.join() except Exception as e: self.log.print("Exception in the main thread: ",format(e)) # self.database.get_user('71f7bb0c6db392201e3c')
def search2(string, page): """ Fonction appelee pour la recherche de films et series correspondant a "string", permet d'aller a la page de resultats de recherche :param string: string. Recherche effectuée par l'utilisateur :param page: int. Numéro de la page des résultats :return: """ list_series, list_movies, nb_pages = Api.search(string, page) app.logger.info(msg=f'Search page {page} rendered for : {string}') return render_template('search.html', title='Search', list_series=list_series, tv_genres=tv_genres, movie_genres=movie_genres, list_movies=list_movies, nb_pages=nb_pages, current_page=int(page), search=string)
def topRated(media, page): """ This function is called when the user tries to access the popular pannel from one of the pages We start by getting the API result with the API class :param media:String (movie or tv) :param page:int (>0) :return:void """ # we get the result from the API top_rated_medias, nb_pages = Api.get_top_rated(media, page) app.logger.info(msg=f'Top Rated request on Media = {media}, Page = {page}') return render_template('topRatedMedias.html', list_medias=top_rated_medias, current_page=int(page), media=media, page=page, nb_pages=nb_pages, tv_genres=tv_genres, movie_genres=movie_genres)
def media(type_media, id): ''' Route pour accéder à la page des détails d'un média (série ou film) :param type_media: string. Type du média : 'tv' ou 'movie' :param id: int. Id du média :return: ''' media = Api.get_media(type_media=type_media, id_media=id) similar = Api.get_similar(id=id, media_type=type_media) if media is None: app.logger.info(msg=f'Incorrect {type_media} id') return render_template('404.html') else: app.logger.info(msg=f'Successful query for the {type_media} id={media.id} page') if type_media == 'tv': if current_user.is_in_medias(id_media=id, type_media=type_media): media.selected_episode = current_user.get_last_episode_viewed(id) episode = media.get_episode return render_template('serie.html', media=media, episode=episode, user=current_user, type_media=type_media, tv_genres=tv_genres, movie_genres=movie_genres, similar=similar) else: return render_template('movie.html', media=media, user=current_user, type_media=type_media, tv_genres=tv_genres, movie_genres=movie_genres, similar=similar)
def add_media(self, id_media, type_media): """ Cette methode permet d'ajoute un media a l'utilisateur dans la table user_media Par defaut, si le media est une serie, elle commence comme non a jour (nutd) sinon, les champs specifiques a une serie sont laisses vides On met a jour les notifications de l'utilisateur :param id_media: int :return: void """ # On commence par verifier que le media n'est pas deja dans la liste des medias de l'utilisateur if not self.is_in_medias(id_media=id_media, type_media=type_media): if type_media == 'tv': # On ajoute la serie a l'utilisatur en la marquant comme nutd et on remeta jour les notifications serie_info = Api.get_media(type_media='tv', id_media=int(id_media)) last_season, last_ep = serie_info.latest[ 'season_number'], serie_info.latest['episode_number'] status = '' # Si le dernier episode vu par l'utilisateur est le dernier episode selon l'API, on regarde si il y a un # episode attendu pour savoir si l'utilisateur est a la fin de la serie if not self.is_after( season=last_season, episode=last_ep, serie=id_media): if serie_info.date == '': # On met a jour le statut de la serie en finie (fin) status = 'fin' else: status = 'utd' else: status = 'nutd' m = UserMedia(media='tv', media_id=int(id_media), season_id=1, episode_id=1, state_serie=status, user=self, media_name=serie_info.name) self.notifications = bytes(1) else: m = UserMedia(media='movie', media_id=int(id_media), user=self) # On inscrit les changements dans la base de donnees db.session.add(m) db.session.commit()
def __init__(self, id, id_serie ,season_number,episode_count, listEpisodes, grade, image): """ Constructeur de notre classe saison, on considère que toutes les informations sont données par l'API lors de la construction d'une nouvelle série :param id: l'identifiant private de notre classe, elle est private et sans mutateur :param episode_count: le nombre d'épisodes de notre saison, elle est private :param episode: le dictionnaire qui permet de stocker les épisodes déjà consultés pour la saison :param notes: les notes données par les utilisateurs, elles sont private :param image: l'image de la saison qui est private """ self.id_serie = id_serie self._id = id self.episode_count = episode_count self.season_number = season_number self._listEpisode = listEpisodes self.grade = grade self._image = image self.selected_episode = Api.get_episode(self.id_serie, self.season_number, 1)
def genre(media, genre, page): """ Cette route permet d'accéder à la page qui recense tous les médias d'un certain genre :param media: string. Type de média : 'tv' ou 'movie' :param genre: string. Nom du genre :param page: int. Numéro de la page des résultats :return: """ if media == 'movie': list_genres = movie_genres else : list_genres = tv_genres for i in range(len(list_genres)): if list_genres[i]['name'] == genre: index_genre = i id_genre = list_genres[index_genre]['id'] list_media, nb_pages = Api.discover(media, id_genre, page) app.logger.info(msg=f'Genre request on : Genre = {genre}, Media = {media}, Page = {page}') return render_template('genre.html', genre=genre, list_medias=list_media, media=media, tv_genres=tv_genres, movie_genres=movie_genres, current_page=int(page), nb_pages=nb_pages)
def my_media(type_media): """ Fonction appelee pour avoir la page correspondant a la liste des films ou des series ajoutes par l'utilisateur :param type_media: string. Type du média : 'tv' ou 'movie' :return: void """ list_medias = current_user.list_media(media=type_media) list_medias_rendered =[] nb_medias = 0 if not list_medias: app.logger.info(msg=f"My{type_media}s page rendered without {type_media}s") else: for m in list_medias: nb_medias += 1 media = Api.get_media(type_media=type_media, id_media=m) list_medias_rendered.append(media) app.logger.info(msg=f'My{type_media}s page rendered') app.logger.info(msg=f'The {type_media} list has {nb_medias} {type_media}s') return render_template('myMedias.html', title=f'My{type_media}', type_media=type_media, list_medias=list_medias_rendered, nb_medias=nb_medias, tv_genres=tv_genres, movie_genres=movie_genres, user=current_user)
def update_all_upcoming_episodes(self): """ Cette methode est appelee lorsque l'user se connecte sur le site Avec cette methode, on met a jour les statuts de tous les series de l'utilisateur Pour ce faire, on parcourt la liste des series de l'utilisateur et on compare le dernier episode vu par l'utilisateur avec le dernier episode de la serie selon l'API. Si l'utilisateur est au dernier, on regarde si l'API contient un episode futur On ne lance cette methode qu'a chaque connexions de l'utilisateur afin de ne pas trop appeler l'API :return: void """ # On recupere toutes les series de l'utilisateur serie = self.user_media.filter_by(media='tv').all() for s in serie: # On recupere les infos de chaque serie grace a l'API serie_info = Api.get_media(type_media='tv', id_media=s.media_id) # On recupere les infos de l'API sur le dernier episode last_season, last_ep = serie_info.latest[ 'season_number'], serie_info.latest['episode_number'] status = '' # Si le dernier episode vu par l'utilisateur est le dernier episode selon l'API, on regarde si il y a un # episode attendu pour savoir si l'utilisateur est a la fin de la serie if not self.is_after( season=last_season, episode=last_ep, serie=s.media_id): if serie_info.date == '': # On met a jour le statut de la serie en finie (fin) status = 'fin' else: status = 'utd' else: status = 'nutd' # On met a jour le statut dans la BDD s.state_serie = status db.session.commit()
class Main(): filter = None #inicia a variavel com o objecto vazio def __init__(self): self.g = Api() # Vai buscar a class API do ficheiro api.py # Janela Principal self.main_window = QMainWindow() self.main_window_form = Ui_MainWindow() self.main_window_form.setupUi(self.main_window) self.main_window.show() # Janela Adicionar self.main_window2 = QMainWindow() self.main_window_form2 = Ui_MainWindow2() self.main_window_form2.setup(self.main_window2) # Janela Modificar self.main_window4 = QMainWindow() self.main_window_form4 = Ui_MainWindow4() self.main_window_form4.setup4(self.main_window4) # Janela Pesquisar self.main_window5 = QMainWindow() self.main_window_form5 = Ui_MainWindow5() self.main_window_form5.setup5(self.main_window5) # Janela Mostrar Imagem self.main_window6 = QMainWindow() self.main_window_form6 = Ui_MainWindow6() self.main_window_form6.setup6(self.main_window6) self.bindings( ) #chamar a funçao bindings a class , para que os butoes consigam "correr" self.database( ) #chamar a funcao database, para que mostra a base de dados no inicio def bindings(self): #Funçao onde se conectao todos os botoes self.main_window_form.add_pushButton_2.clicked.connect( self.show_jn2) # mostra a janela "Adicionar" self.main_window_form2.guardar_pushButton.clicked.connect( self.guardar ) # quando carrega em guardar corre a funçao "def guardar" self.main_window_form2.cancelar_pushButton.clicked.connect( self.hide2 ) # quando clica em cancelar corre a funcao "def hide2" que faz esconder a janela self.main_window_form.remove_pushButton_4.clicked.connect( self.remover) # quando é clicado corre a funçao "def remover" self.main_window_form4.novo_cancelar_pushButton.clicked.connect( self.hide4 ) # quando clica em cancelar corre a funcao "def hide4" que faz esconder a janela self.main_window_form.modify_pushButton_3.clicked.connect( self.show_jn4 ) # mostra a janela da funçao "def show_jn4", quando carregamos em modificar self.main_window_form4.novo_guardar_pushButton.clicked.connect( self.modificar ) # quando carregamos em modificar corre a funçao "def modificar" self.main_window_form2.imagem_pushButton.clicked.connect(self.explorer) self.main_window_form4.novo_imagem_pushButton.clicked.connect( self.explorer) self.main_window_form.search_pushButton.clicked.connect(self.show_jn5) self.main_window_form5.cancelar_pushButton.clicked.connect(self.hide5) self.main_window_form6.sair_pushbutton.clicked.connect(self.hide6) self.main_window_form.treeWidget.doubleClicked.connect(self.show_jn6) self.main_window_form5.pesquisar_pushButton.clicked.connect( self.button_pesquisar) self.main_window_form.reset_pushButton.clicked.connect( self.update_database ) #quando se clicla no botao reset conecta-se a funçao "def clear_database" self.main_window_form5.preco_checkBox.clicked.connect( self.ativa_precos) self.main_window_form5.data_checkBox.clicked.connect(self.ativa_data) self.main_window_form.exportar_pushButton.clicked.connect( self.extrair_csv) self.main_window_form.importar_pushButton.clicked.connect( self.import_csv) def guardar(self): inp = self.main_window_form2.preco_lineEdit.text( ) # guarda o input de preço em inp try: preco = float(inp) # verifica se preço é um float except ValueError: # Se nao for, aparece uma janela de "Erro!", e repete o processo msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("O valor é invalido!") msg.exec_() return if self.main_window_form2.nome_lineEdit.text( ) == "": #se o nome estiver em branco, mostra uma mensagem, e repete o processo msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("Tem de introduzir um Nome") msg.exec_() return if self.main_window_form2.marca_lineEdit.text() == "": msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("Tem de introduzir uma Marca") msg.exec_() return if self.main_window_form2.imagem_lineEdit.text() == "": msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("Tem de introduzir uma Imagem!") msg.exec_() return self.g.add_artigo(nome=self.main_window_form2.nome_lineEdit.text(), marca=self.main_window_form2.marca_lineEdit.text(), preco=preco, imagem=self.main_window_form2.imagem_lineEdit.text() ) # funçao que corre na "api.py" "def add_artigo" self.hide2() self.update_database( ) #insere-a de novo com as alteraçoes feitas pelo utilizador def remover(self): get_Selected = self.main_window_form.treeWidget.selectedItems( ) # seleção do artigo que o utilizador pretende if get_Selected: # se selecionada remove = get_Selected[0].text(0) # vai buscar o artigo selecionado self.g.remove_artigo(remove) # remove o artigo self.update_database() #limpa, e insere a base de dados na treewidget def modificar(self): inp = self.main_window_form4.novo_preco_lineEdit.text( ) #a ediçao do preco é contida na variavel inp try: #utilizador tenta introduzir um float, caso de erro aparece uma menssagem "O valor é invalido" preco = float(inp) #variavel tranformada para um float except ValueError: msg = QMessageBox( ) #Introduz na variavel msg a janela de texto(widget do pyqt5) msg.setWindowTitle("Erro!") #Titulo da janela de texto msg.setText( "O valor é invalido!") #Introduz a Menssagem que queremos msg.exec_() #executa return #volta a repetir o processo sem parar o programa get_modificar = self.main_window_form.treeWidget.selectedItems( ) # seleção do artigo que o utilizador pretende if get_modificar: #se o artigo for selecionado artigo_selecionado = get_modificar[0].text( 0) #artigo selecionado com o texto que a seleçao se identifica if self.main_window_form4.novo_nome_lineEdit.text( ) == "": #na janela modificar, se a linha onde se introduz o nome estiver em branco msg = QMessageBox( ) #Introduz na variavel msg a janela de texto(widget do pyqt5) msg.setWindowTitle("Erro!") #Titulo da janela de texto msg.setText( "Introduza um Nome") #Introduz a Menssagem que queremos msg.exec_() #executa return #volta a repetir o processo sem parar o programa if self.main_window_form4.novo_marca_lineEdit.text() == "": msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("Introduza uma Marca") msg.exec_() return if self.main_window_form4.novo_imagem_lineEdit.text() == "": msg = QMessageBox() msg.setWindowTitle("Erro!") msg.setText("Introduza uma Imagem") msg.exec_() return self.g.modificar_artigo( artigo_selecionado, novo_nome=self.main_window_form4.novo_nome_lineEdit.text(), novo_marca=self.main_window_form4.novo_marca_lineEdit.text(), novo_preco=preco, novo_imagem=self.main_window_form4.novo_imagem_lineEdit.text()) #inicia a funçao que esta na api.Api() def modificar_artigo, em que, o artigo selecionado self.hide4( ) #inicia a def hide4, que faz esconder a janela depois de modificar self.update_database( ) #introduz a funçao def resest_database, para introduzir de novo a base de dados com as alterações def explorer(self): file = QFileDialog( ) #class que promove que os utilizadores permitam a selecao de ficheiros ou diretório file.setFileMode(QFileDialog.ExistingFile) #o ficheiro tem de existir if file.exec_(): # se a procura de ficheiros incia filenames = file.selectedFiles( ) #os ficheiros selecionados(o diretorio), terao como variavel "filenames" self.main_window_form2.imagem_lineEdit.setText( filenames[0]) #para a linha de ediçao da janela # main_windows_form2(janela de adicionar), com o nome imagem_lineedit, insere o texto da variavel filenames self.main_window_form4.novo_imagem_lineEdit.setText( filenames[0]) #repete-se a mesma coisa para a janela Modificar def pesquisar(self): self.main_window_form5.min_doubleSpinBox.setDisabled( True) #Desativar o preco minimo self.main_window_form5.max_doubleSpinBox.setDisabled( True) #Desativar o preço maximo self.main_window_form5.min_dateTimeEdit.setDisabled( True) #Desativar a data minima self.main_window_form5.max_dateTimeEdit.setDisabled( True) #Desativar a data maxima nome = db.session.query(db.Artigo.nome).all( ) #vai buscar todos os artigos.nome da base de dados e introduz na variavel nome self.main_window_form5.nome_comboBox.clear( ) #apaga tudo o que tiver na combobox da janela pesquisar self.main_window_form5.nome_comboBox.addItem( "" ) #adiciona um item em branco, para que seja possivel pesquisar uma marca ou preço, sem introduzir um nome lista_nome = [] #cria uma lista for i in nome: #para a variavel i em nome faz: if i not in lista_nome: #se i nao está na lista_nome lista_nome.append( i ) #adiciona i à lista_nome, ou seja, i esta dentro da variavel nome self.main_window_form5.nome_comboBox.addItem( i[0]) #adiciona i a combobox Nome: self.main_window_form5.nome_comboBox.setCurrentText( None ) #para combobox nome na janela pesquisar, para o valor inicial nao ira ter nenhum objecto atribuido #Isto é para a combobox do nome e marca, apaga tudo, adiciona uma string em branco, verifica se os objectos da lista #sao repetidos, se nao forem adiciona, se forem nem se quer aparecem, e o ojecto inical é nenhum(None) marca = db.session.query(db.Artigo.marca).all() self.main_window_form5.marca_comboBox.clear() self.main_window_form5.marca_comboBox.addItem("") lista_marca = [] for i in marca: if i not in lista_marca: lista_marca.append(i) self.main_window_form5.marca_comboBox.addItem(i[0]) self.main_window_form5.marca_comboBox.setCurrentText(None) #É a mesma coisa que o nome, mas agora para a marca def ativa_precos(self): if self.main_window_form5.preco_checkBox.isChecked( ): #se a checkbox estiver com o visto self.main_window_form5.min_doubleSpinBox.setEnabled( True) #ativa a min_doublespinbox self.main_window_form5.max_doubleSpinBox.setEnabled( True) #ativa a max_doublespinbox else: #se nao estiver com o visto self.main_window_form5.min_doubleSpinBox.setEnabled( False) #desativa self.main_window_form5.max_doubleSpinBox.setEnabled(False) def ativa_data(self): #é igual a função do ativa_precos so que para a data if self.main_window_form5.data_checkBox.isChecked(): self.main_window_form5.min_dateTimeEdit.setEnabled(True) self.main_window_form5.max_dateTimeEdit.setEnabled(True) else: self.main_window_form5.min_dateTimeEdit.setEnabled(False) self.main_window_form5.max_dateTimeEdit.setEnabled(False) def button_pesquisar(self): nome = self.main_window_form5.nome_comboBox.currentText( ) # retira o valor contido no nome da janela pesquisar marca = self.main_window_form5.marca_comboBox.currentText( ) # retira o valor contido na marca da janela pesquisar if self.main_window_form5.preco_checkBox.isChecked( ): #se a checkbox tiver o visto preco_min = self.main_window_form5.min_doubleSpinBox.value( ) #retira o valor que esta inserido e mete-o na variavel preco_min preco_max = self.main_window_form5.max_doubleSpinBox.value( ) #retira o valor que esta inserido e mete-o na variavel preco_max else: #se nao tiver o visto preco_min = None #preco_min é igual a None preco_max = None #preco_max é igual a None #repete-se para a data if self.main_window_form5.data_checkBox.isChecked(): data_min = self.main_window_form5.min_dateTimeEdit.date( ) #Imprime a data "PyQt5.QtCore.QDate(2019, 05, 20)" datascrap_min = data_min.toPyDate() #Imprime 2019-05-20 data_max = self.main_window_form5.max_dateTimeEdit.date( ) #Imprime a data "PyQt5.QtCore.QDate(2019, 05, 20)" datascrap_max = data_max.toPyDate() #Imprime 2019-05-20 else: datascrap_min = None datascrap_max = None self.filter = { "nome": nome, "marca": marca, "preco": [preco_min, preco_max], "datascrap": [datascrap_min, datascrap_max] } self.hide5() #esconde a janela de pesquisa self.database() #insere a base de dados def database(self): if self.filter is not None: #se houver filtro artigo = db.session.query( db.Artigo) #manda um query a base de dados if self.filter["nome"]: #se filtro for no nome query = db.session.query(db.Artigo).filter_by( nome=self.filter["nome"] ) #manda um query a base de dados para filtrar por nome artigo = artigo.intersect( query ) #tudo o que estiver na base de dados é interceptado com o query do nome if self.filter["marca"]: query = db.session.query( db.Artigo).filter_by(marca=self.filter["marca"]) artigo = artigo.intersect(query) if self.filter["preco"][0] is not None or self.filter["preco"][ 1] is not None: query = db.session.query(db.Artigo).filter(db.Artigo.preco >= self.filter["preco"][0])\ .filter(db.Artigo.preco <= self.filter["preco"][1]) #recolhe todos os valor que estao entre o preço minimo e o preço maximo artigo = artigo.intersect(query) #interceção dos artigos if self.filter["datascrap"][0] is not None or self.filter[ "datascrap"][1] is not None: query = db.session.query(db.Artigo).filter(db.Artigo.data_scrap >= self.filter["datascrap"][0])\ .filter(db.Artigo.data_scrap <= self.filter["datascrap"][1]) # recolhe todas as datas, entre as datas escolhidas artigo = artigo.intersect(query) else: #se nao tiver filtros artigo = db.session.query(db.Artigo).all( ) #manda um pedido a base de dados para recolher todos os artigos que se encontram na db.Artigo self.main_window_form.treeWidget.clear( ) #limpa a janela que mostra a base de dados for i in artigo: #para i em artigos item = QTreeWidgetItem([ str(i.id), i.nome, i.marca, str(i.preco), str(i.data_scrap).split(" ")[0], str(i.imagem) ]) self.main_window_form.treeWidget.addTopLevelItem( item ) #adiciona a janela de demostração os items recolhidos em artigos def update_database( self ): #limpa a janela de visualizaçao da database e insere-a de novo artigo = db.session.query(db.Artigo).all() self.main_window_form.treeWidget.clear() for i in artigo: item = QTreeWidgetItem([ str(i.id), i.nome, i.marca, str(i.preco), str(i.data_scrap).split(" ")[0], str(i.imagem) ]) self.main_window_form.treeWidget.addTopLevelItem(item) def extrair_csv(self): if self.filter is not None: artigo = db.session.query( db.Artigo) # manda um query a base de dados if self.filter["nome"]: # se filtro for no nome query = db.session.query(db.Artigo).filter_by( nome=self.filter["nome"] ) # manda um query a base de dados para filtrar por nome artigo = artigo.intersect( query ) # tudo o que estiver na base de dados é interceptado com o query do nome if self.filter["marca"]: query = db.session.query( db.Artigo).filter_by(marca=self.filter["marca"]) artigo = artigo.intersect(query) if self.filter["preco"][0] is not None or self.filter["preco"][ 1] is not None: query = db.session.query(db.Artigo).filter(db.Artigo.preco >= self.filter["preco"][0]) \ .filter(db.Artigo.preco <= self.filter["preco"][1]) # recolhe todos os valor que estao entre o preço minimo e o preço maximo artigo = artigo.intersect(query) # interceção dos artigos if self.filter["datascrap"][0] is not None or self.filter[ "datascrap"][1] is not None: query = db.session.query(db.Artigo).filter(db.Artigo.data_scrap >= self.filter["datascrap"][0]) \ .filter(db.Artigo.data_scrap <= self.filter["datascrap"][1]) # recolhe todas as datas, entre as datas escolhidas artigo = artigo.intersect(query) else: # se nao tiver filtros artigo = db.session.query(db.Artigo).all() file = './Ficheiros/export.csv' with open(file, 'w') as csvfile: outcsv = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) cabecalho = db.Artigo.__table__.columns.keys() outcsv.writerow(cabecalho) for gravar in artigo: outcsv.writerow([getattr(gravar, c) for c in cabecalho]) msg = QMessageBox() msg.setWindowTitle("Verificação!") msg.setText("O seu ficheiro foi exportado") msg.exec_() def import_csv(self): import_csv() self.update_database() def show_jn2(self): self.main_window2.show() # mostrar a janela Adicionar def show_jn4( self ): #imprime os campos na janela de modificar, o artigo selecionado get_Selected = self.main_window_form.treeWidget.selectedItems() if get_Selected: id = get_Selected[0].text(0) artigo = db.session.query(db.Artigo).filter_by(id=id).first() self.main_window_form4.novo_nome_lineEdit.setText(artigo.nome) self.main_window_form4.novo_marca_lineEdit.setText(artigo.marca) self.main_window_form4.novo_preco_lineEdit.setText( str(artigo.preco)) self.main_window_form4.novo_imagem_lineEdit.setText( str(artigo.imagem)) self.main_window4.show() # mostra a janela def show_jn5(self): self.main_window5.show() # mostra a janela do pesquisar self.pesquisar() def show_jn6(self): get_Selected = self.main_window_form.treeWidget.selectedItems( ) # seleção do artigo que o utilizador pretende if get_Selected: # se selecionada id = get_Selected[0].text( 0) # regista id da seleçao e guarda na variavel id artigo = db.session.query(db.Artigo).filter_by(id=id).first() self.main_window_form6.id_lineEdit.setText( str(artigo.id) ) # apresenta o id do artigo selecionado é convertido em str # para visualizar, porque verdadeiramente o id é um inteiro como se pode ver na pasta api.py self.main_window_form6.nome_lineEdit.setText( artigo.nome) # apresenta o nome do artigo selecionado self.main_window_form6.marca_lineEdit.setText( artigo.marca) # apresenta a marca do artigo selecionado self.main_window_form6.preco_lineEdit.setText(str(artigo.preco)) self.main_window_form6.datascrap_lineEdit.setText( str(artigo.data_scrap)) self.main_window_form6.imagem_lineEdit.setText(str(artigo.imagem)) pixmap = QPixmap( artigo.imagem ) # "converte" o directorio, para a variavel pixmap pixmap = pixmap.scaled( 400, 400 ) #redimensiona a foto para 400*400 que é o tamanho da "label" self.main_window_form6.imagem_label.setPixmap( pixmap ) # apresenta a imagem na label(widget utilizado no qtdesigner) self.main_window6.show() #mostra a janela do artigo selecionado def hide2(self): self.main_window2.hide() # esconde a janela def hide4(self): self.main_window4.hide() # esconde a janela def hide5(self): self.main_window5.hide() def hide6(self): self.main_window6.hide()
def setUp(self): self.api = Api()
from django.urls import include, path from app.api import Api api = Api() urlpatterns = ([ path('codes/', api.show_codes), path('currency/all/', api.show_all_currencies), path('currency/<str:from_code>/<str:to_code>/', api.show_currency), ])
Fichier de routage depuis lequel on accède aux différentes pages du site ''' from flask import render_template, redirect, url_for, flash, request, g from app.api import Api from app import app, db from app.forms import LoginForm, RegistrationForm, ResetPasswordRequestForm, ResetPasswordForm, SearchForm from app.mail import send_password_reset_email from flask_login import current_user, login_user from app.models import User from flask_login import logout_user from flask_login import login_required from werkzeug.urls import url_parse from datetime import datetime tv_genres = Api.get_genre('tv') movie_genres = Api.get_genre('movie') logo_nom_source = "../static/assets/LogoNom.png" logo_source = "../static/assets/Logo.png" @app.route('/') @app.route('/home') @login_required def home(): """ Cette fonction permet de retourner la home page de notre site qui indique les dernieres sorties de series et films. On passe egalement les genres de series et de films en parametres pour la sidebar :return:void """ suggestions_serie = Api.get_popular('serie', 1)
from flask import Flask, render_template, session, request from flask_sqlalchemy import SQLAlchemy from app.api import Api app = Flask(__name__) app.config.from_object("config") db = SQLAlchemy(app) api = Api(db) class Alert: @staticmethod def alert(message, kind): if not "alerts" in session: session["alerts"] = [] session["alerts"].append((message, kind)) @staticmethod def good(message): Alert.alert(message, "alert-success") @staticmethod def bad(message): Alert.alert(message, "alert-danger") def querystring_get(key, alternate=""): return request.form[key].strip() if key in request.form else alternate @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404