Best Python code snippet using tempest_python
main.py
Source:main.py  
1import pickle2import sys3import pygame4from PyQt5 import QtWidgets5from Gestione_Ascolto.Controller.controller_ascolto import controller_mostra_search, controller_mostra_tutto6from Gestione_del_profilo.Controller.Controller_artista import controller_artista7from Gestione_del_profilo.Controller.Controller_ascoltatore import controller_ascoltatore8from Gestione_del_profilo.Controller.Controller_conferma_credenziali import controller_conferma_credenziali9from Gestione_del_profilo.Controller.Controller_conferma_edit import controller_conferma_edit10from Gestione_del_profilo.Controller.Controller_easter_egg import controller_easter_egg11from Gestione_del_profilo.Controller.Controller_edit_artista import controller_edit_artista12from Gestione_del_profilo.Controller.Controller_edit_ascoltatore import controller_edit_ascoltatore13from Gestione_del_profilo.Controller.Controller_impostazioni import controller_impostazioni14from Gestione_del_profilo.Controller.Controller_impostazioni_ascoltatore import controller_impostazioni_ascoltatore15from Gestione_del_profilo.Controller.controller_conferma_eliminazione import controller_conferma_eliminazione16from Gestione_del_profilo.Controller.controller_etichetta import controller_etichetta17from Login.Model.login import DataPick18from Login.controller.controller_login import Login19from Pubblicazione.Controller.Controller_Caricamento_Brano_Etichetta import Controller_Caricamento_Brano_Etichetta20from Pubblicazione.Controller.Controller_caricamento_album import Controller_caricamento_album21from Pubblicazione.Controller.Controller_pubblicazione_inizio import controller_pubblicazione_inizio22from Pubblicazione.Controller.Controller_Caricamento_Brano_Artista import Controller_Caricamento_Brano_artista_Artista23from Pubblicazione.Model.pubblicazione_gestione import Gestione_json24from Top5.Controller.ControllerTop5 import TopFive25from Gestione_del_profilo.Controller.Controller_rimozione_brani import controller_rimozioni_brani26from Registrazione.controller.controller_registrazione import Newuser27class Controller():28    def __init__(self):29        '''--variabili per chiusura delle classi--'''30        self.check_login_page = False31        self.check_newuser_page = False32        self.check_home_ascoltatore = False33        self.check_home_artista = False34        self.check_home_etichetta = False35        self.check_pubblicazione_inizio1 = False36        self.check_pubblicazione_brano = False37        self.check_impostazioni_ascoltatore = False38        self.check_edit_ascoltatore = False39        self.check_impostazioni_artista = False40        self.check_edit_artista = False41        self.check_impostazioni_etichetta = False42        self.check_conferma_credenziali = False43        self.check_conferma_edit = False44        self.check_mostra_tutto = False45        self.check_mostra_search = False46        self.check_verifica_etichetta = False47        self.check_richiesta_nBrani1 = False48        self.check_pubblicazione_brano_etichetta1 = False49        self.check_easter_egg = False50        self.check_rimozione_brani = False51        self.check_scelta_rimozione_brano = False52        '''--variabili per funzionamento pubblicazione--'''53        self.check_pubblicazione_brano_artista = False54        self.pippo= 055        #self.Richiesta_nBrani = Controller_Richiesta_nBrani()56        #self.check_pubblicazione_album = self.Richiesta_nBrani.verifica_album57        self.conta_brani_artista = 058        self.conta_brani_etichetta = 059        60    """FINESTRA POP UP"""61    def pop_message(self, text=""):62        msg = QtWidgets.QMessageBox()63        msg.setText("{}".format(text))64        msg.exec_()65    def show_login_page(self):66        self.login = Login()67        self.login.switch_window.connect(self.show_newuser_page)68        self.login.switch_window1.connect(self.show_home_ascoltatore)69        self.login.switch_window2.connect(self.show_home_artista)70        self.login.switch_window3.connect(self.show_home_etichetta)71        if self.check_newuser_page is True:72            self.newuser.close()73            self.check_newuser_page = False74        self.check_login_page = True75        self.login.show()76    def show_newuser_page(self):77        self.newuser = Newuser()78        self.newuser.switch_window.connect(self.show_login_page)79        if self.check_login_page is True:80            self.login.close()81            self.check_login_page = False82        self.check_newuser_page = True83        self.newuser.show()84    """---------------------------------------------------------------------------------------------"""85    """Home PyLemon"""86    def show_home_ascoltatore(self):87        Titoli_top = self.statistica_top5()88        self.ascoltatore = controller_ascoltatore(Titoli_top)89        self.ascoltatore.switch_window_1.connect(self.show_impostazioni_ascoltatore)90        self.ascoltatore.switch_window_2.connect(self.show_mostra_tutto)91        self.ascoltatore.switch_window_4.connect(self.show_mostra_search)92        self.ascoltatore.switch_window_5.connect(self.show_easter_egg)93        self.ascoltatore.switch_window_k.connect(self.show_logout)94        if self.check_login_page is True:95            self.login.close()96            self.check_login_page = False97        self.check_home_ascoltatore = True98        self.ascoltatore.show()99    def show_home_artista(self):100        Titoli_top = self.statistica_top5()101        Brani_artisti = self.statistica_mie_brani_artista()102        self.artista = controller_artista(Titoli_top,Brani_artisti)103        self.artista.switch_window_1.connect(self.show_impostazioni_artista)104        self.artista.switch_window_2.connect(self.show_mostra_tutto)105        self.artista.switch_window_3.connect(self.show_pubblicazione_inizio)106        self.artista.switch_window_4.connect(self.show_mostra_search)107        self.artista.switch_window_5.connect(self.show_easter_egg)108        self.artista.switch_window_k.connect(self.show_logout)109        if self.check_login_page is True:110            self.login.close()111            self.check_login_page = False112        if self.check_pubblicazione_brano_artista is True:113            self.Caricamento_Brano_Artista.close()114            self.check_pubblicazione_brano_artista = False115        if self.check_pubblicazione_brano_etichetta1 is True:116            self.Caricamento_Brano_etichetta.close()117            self.check_pubblicazione_brano_etichetta1 = False118        self.check_home_artista = True119        self.artista.show()120    def show_home_etichetta(self):121        Titoli_top = self.statistica_top5()122        self.etichetta = controller_etichetta(Titoli_top)123        self.etichetta.switch_window_3.connect(self.show_pubblicazione_inizio)124        self.etichetta.switch_window_2.connect(self.show_mostra_tutto)125        self.etichetta.switch_window_1.connect(self.show_impostazioni_etichetta)126        self.etichetta.switch_window_4.connect(self.show_mostra_search)127        self.etichetta.switch_window_5.connect(self.show_easter_egg)128        self.etichetta.switch_window_k.connect(self.show_logout)129        self.check_verifica_etichetta = True130        if self.check_pubblicazione_brano_artista is True:131            self.Caricamento_Brano_Artista.close()132            self.check_pubblicazione_brano_artista = False133        if self.check_pubblicazione_brano_etichetta1 is True:134            self.Caricamento_Brano_etichetta.close()135            self.check_pubblicazione_brano_etichetta1 = False136        if self.check_login_page is True:137            self.login.close()138            self.check_login_page = False139        self.check_home_etichetta= True140        self.etichetta.show()141    '''-------------------------------------------------------------------'''142    def show_easter_egg(self):143        self.easter = controller_easter_egg()144        self.check_easter_egg = True145        self.easter.show()146    """---------------------------------------------------------------------------------------------"""147    """Controller pubblicazione"""148    def show_pubblicazione_inizio(self):149        self.pubblicazione_inizio = controller_pubblicazione_inizio()150        self.Richiesta_nBrani = Controller_caricamento_album()151        if self.check_verifica_etichetta:152            self.pubblicazione_inizio.switch_window_1.connect(self.show_pubblicazione_brano_etichetta)153        else:154            self.pubblicazione_inizio.switch_window_1.connect(self.show_pubblicazione_brano_artista)155        self.pubblicazione_inizio.switch_window_2.connect(self.show_pubblicazione_album)156        if self.check_pubblicazione_brano_artista is True:157            self.Caricamento_Brano_Artista.close()158            self.check_pubblicazione_brano_artista = False159        if self.Richiesta_nBrani.verifica_album is True:160            if self.conta_brani_artista == int(self.nBrani):161                self.Richiesta_nBrani.verifica_album =False162        if self.check_pubblicazione_brano_etichetta1 is True:163            if self.Richiesta_nBrani.verifica_album is True:164                if self.conta_brani_etichetta == int(self.nBrani_etichetta):165                    self.Caricamento_Brano_etichetta.close()166                    self.check_pubblicazione_brano_etichetta1 = False167            else:168                self.Caricamento_Brano_etichetta.close()169                self.check_pubblicazione_brano_etichetta1 = False170        if self.check_richiesta_nBrani1 is True:171            self.Richiesta_nBrani.close()172            self.check_richiesta_nBrani1= False173        self.check_pubblicazione_inizio1 = True174        self.pubblicazione_inizio.show()175    def show_pubblicazione_brano_artista(self):176        self.Richiesta_nBrani = Controller_caricamento_album()177        if self.check_pubblicazione_inizio1 is True:178            self.pubblicazione_inizio.close()179            self.check_pubblicazione_inizio1 = False180        if self.check_richiesta_nBrani1 is True:181            self.Richiesta_nBrani.close()182            self.check_richiesta_nBrani1 = False183        with open('Data/Database/Album.pkl', 'rb') as Dpi:184            MyData = pickle.load(Dpi)185        if int(MyData[0]) == 0:186            self.verifica_album = False187        else: self.verifica_album = True188        if  int(MyData[0]) > 1:189            self.conta_brani_artista = self.conta_brani_artista + 1190            self.nome_album = MyData[1]191        else: self.nome_album = None192        self.Caricamento_Brano_Artista = Controller_Caricamento_Brano_artista_Artista(self.verifica_album, self.nome_album)193        self.Caricamento_Brano_Artista.switch_window_1.connect(self.show_home_artista)194        self.Caricamento_Brano_Artista.switch_window_3.connect(self.show_pubblicazione_brano_artista)195        if  int(MyData[0]) > 0:196            if self.conta_brani_artista == int(MyData[0]):197                self.Richiesta_nBrani.put_data_brani('0','0')198                self.conta_brani_artista = 0199                self.Caricamento_Brano_Artista.controllo_fine_album = True200            else:201                self.Caricamento_Brano_Artista.controllo_fine_album = False202        if int(MyData[0]) > 0:203            self.Caricamento_Brano_Artista.switch_window_2.connect(self.show_pubblicazione_album)204        else: self.Caricamento_Brano_Artista.switch_window_2.connect(self.show_pubblicazione_inizio)205        self.check_pubblicazione_brano_artista = True206        self.Caricamento_Brano_Artista.show()207    def show_pubblicazione_brano_etichetta(self):208        self.Richiesta_nBrani = Controller_caricamento_album()209        if self.check_richiesta_nBrani1 is True:210            self.Richiesta_nBrani.close()211            self.check_richiesta_nBrani1 = False212        if self.check_pubblicazione_inizio1 is True:213            self.pubblicazione_inizio.close()214            self.check_pubblicazione_inizio1 = False215        with open('Data/Database/Album.pkl', 'rb') as Dpi:216            MyData = pickle.load(Dpi)217        if int(MyData[0]) == 0:218            self.verifica_album = False219        else: self.verifica_album = True220        if  int(MyData[0]) > 1:221            self.conta_brani_etichetta = self.conta_brani_etichetta + 1222            self.nome_album_etichetta = MyData[1]223        else: self.nome_album_etichetta = None224        self.Caricamento_Brano_etichetta = Controller_Caricamento_Brano_Etichetta(self.verifica_album, self.nome_album_etichetta)225        self.Caricamento_Brano_etichetta.switch_window_1.connect(self.show_home_etichetta)226        self.Caricamento_Brano_etichetta.switch_window_3.connect(self.show_pubblicazione_brano_etichetta)227        if  int(MyData[0]) > 0:228            if self.conta_brani_etichetta == int(MyData[0]):229                self.Richiesta_nBrani.put_data_brani('0','0')230                self.conta_brani_etichetta = 0231                self.Caricamento_Brano_etichetta.controllo_fine_album = True232            else:233                self.Caricamento_Brano_etichetta.controllo_fine_album = False234        if int(MyData[0]) > 0:235            self.Caricamento_Brano_etichetta.switch_window_2.connect(self.show_pubblicazione_album)236        else: self.Caricamento_Brano_etichetta.switch_window_2.connect(self.show_pubblicazione_inizio)237        self.check_pubblicazione_brano_etichetta1= True238        self.Caricamento_Brano_etichetta.show()239    def show_pubblicazione_album(self):240        self.Richiesta_nBrani = Controller_caricamento_album()241        if self.check_pubblicazione_inizio1 is True:242            self.pubblicazione_inizio.close()243            self.check_pubblicazione_inizio1 = False244        if self.check_pubblicazione_brano_etichetta1 is True:245            self.Caricamento_Brano_etichetta.close()246            self.check_pubblicazione_brano_etichetta1 = True247        if self.check_verifica_etichetta:248            self.Richiesta_nBrani.switch_window.connect(self.show_pubblicazione_brano_etichetta)249        else:250            self.Richiesta_nBrani.switch_window.connect(self.show_pubblicazione_brano_artista)251        self.Richiesta_nBrani.switch_window_2.connect(self.show_pubblicazione_inizio)252        if self.check_pubblicazione_brano_artista is True:253            self.Caricamento_Brano_Artista.close()254            self.check_pubblicazione_brano_artista = False255        self.check_richiesta_nBrani1 = True256        self.Richiesta_nBrani.show()257    """---------------------------------------------------------------------------------------------"""258    """Controller impostazioni ascoltatore"""259    def show_impostazioni_ascoltatore(self):260        self.impostazioni_ascoltatore = controller_impostazioni_ascoltatore()261        self.impostazioni_ascoltatore.switch_window_1.connect(self.show_conferma_edit)262        self.impostazioni_ascoltatore.switch_window.connect(self.show_conferma_credenziali)263        if self.check_edit_ascoltatore is True:264            self.EditAscoltatore.close()265            self.check_edit_ascoltatore = False266        if self.check_conferma_credenziali is True:267            self.conferma_credenziali.close()268            self.check_conferma_credenziali = False269        if self.check_conferma_edit is True:270            self.conferma_edit.close()271            self.check_conferma_edit = False272        self.check_impostazioni_ascoltatore = True273        self.impostazioni_ascoltatore.show()274    def show_edit_ascoltatore(self):275        self.EditAscoltatore = controller_edit_ascoltatore()276        self.EditAscoltatore.switch_window_1.connect(self.show_impostazioni_ascoltatore)277        self.EditAscoltatore.btn_Artista.clicked.connect(self.show_logout)278        self.EditAscoltatore.btn_Etichetta.clicked.connect(self.show_logout)279        self.impostazioni_ascoltatore.close()280        if self.check_conferma_edit is True:281            self.conferma_edit.close()282            self.check_conferma_edit = False283        self.check_edit_ascoltatore = True284        self.EditAscoltatore.show()285    """Controller impostazioni artista"""286    def show_impostazioni_artista(self):287        self.impostazioni_artista = controller_impostazioni()288        self.impostazioni_artista.switch_window_1.connect(self.show_conferma_edit)289        self.impostazioni_artista.switch_window.connect(self.show_conferma_credenziali)290        self.impostazioni_artista.switch_window_2.connect(self.show_rimozione_brani)291        if self.check_edit_artista is True:292            self.EditArtista.close()293            self.check_edit_artista = False294        if self.check_conferma_credenziali is True:295            self.conferma_credenziali.close()296            self.check_conferma_credenziali = False297        if self.check_conferma_edit is True:298            self.conferma_edit.close()299            self.check_conferma_edit = False300        if self.check_scelta_rimozione_brano is True:301            self.rimuovi.close()302            self.check_scelta_rimozione_brano = False303        if self.check_rimozione_brani is True:304            self.controlla_eliminazione.close()305            self.check_rimozione_brani = False306        self.check_impostazioni_artista = True307        self.impostazioni_artista.show()308    def show_edit_artista(self):309        self.EditArtista = controller_edit_artista()310        self.EditArtista.switch_window_1.connect(self.show_impostazioni_artista)311        self.EditArtista.btn_Ascoltatore.clicked.connect(self.show_logout)312        self.EditArtista.btn_Etichetta.clicked.connect(self.show_logout)313        self.impostazioni_artista.close()314        if self.check_conferma_edit is True:315            self.conferma_edit.close()316            self.check_conferma_edit = False317        self.check_edit_artista = True318        self.EditArtista.show()319    """Controller impostazioni etichetta"""320    def show_impostazioni_etichetta(self):321        self.impostazioni_etichetta = controller_impostazioni()322        self.impostazioni_etichetta.switch_window_1.connect(self.show_edit_etichetta)323        self.impostazioni_etichetta.switch_window.connect(self.show_conferma_credenziali)324        if self.check_conferma_credenziali is True:325            self.conferma_credenziali.close()326            self.check_conferma_credenziali = False327        self.check_impostazioni_etichetta = True328        self.impostazioni_etichetta.show()329    def show_edit_etichetta(self):330        self.pop_message(text="Il suo account non può subire variazioni.")331    """Controller conferma eliminazione universale"""332    def show_conferma_credenziali(self):333        self.conferma_credenziali = controller_conferma_credenziali()334        self.conferma_credenziali.switch_window_1.connect(self.show_impostazioni_ascoltatore)335        self.conferma_credenziali.switch_window_2.connect(self.show_impostazioni_artista)336        self.conferma_credenziali.switch_window_3.connect(self.show_impostazioni_etichetta)337        self.conferma_credenziali.btn_Ok.clicked.connect(self.show_logout)338        self.check_conferma_credenziali = True339        self.conferma_credenziali.show()340    def show_conferma_edit(self):341        self.conferma_edit = controller_conferma_edit()342        self.conferma_edit.switch_window_1.connect(self.show_impostazioni_ascoltatore)343        self.conferma_edit.switch_window_2.connect(self.show_impostazioni_artista)344        self.conferma_edit.switch_window_3.connect(self.show_impostazioni_etichetta)345        self.conferma_edit.switch_window_4.connect(self.show_edit_ascoltatore)346        self.conferma_edit.switch_window_5.connect(self.show_edit_artista)347        self.check_conferma_edit = True348        self.conferma_edit.show()349    def show_rimozione_brani(self):350        self.controlla_eliminazione = controller_conferma_eliminazione()351        self.controlla_eliminazione.switch_window_1.connect(self.show_impostazioni_artista)352        self.controlla_eliminazione.switch_window_2.connect(self.show_scelta_rimozione_brano)353        self.check_rimozione_brani = True354        self.controlla_eliminazione.show()355    def show_scelta_rimozione_brano(self):356        self.rimuovi = controller_rimozioni_brani()357        self.rimuovi.switch_window_1.connect(self.show_impostazioni_artista)358        if self.check_rimozione_brani is True:359            self.controlla_eliminazione.close()360            self.check_rimozione_brani = True361        if self.check_impostazioni_artista is True:362            self.impostazioni_artista.close()363            self.check_impostazioni_artista = True364        self.check_scelta_rimozione_brano = True365        self.rimuovi.show()366    """Controller Player e ricerca canzoni"""367    def show_mostra_tutto(self):368        self.player = controller_mostra_tutto()369        self.check_mostra_tutto = True370        self.player.show()371    def show_mostra_search(self):372        var_search = False373        with open('Data/Database/Canzone.pkl', 'rb') as Dpi:374            MyData = pickle.load(Dpi)375        if MyData[0]:376            json_manage = Gestione_json()377            for i in json_manage.get_jsonobject():378                if i["Titolo"] == MyData[0].title() or i["Album"] == MyData[0].title() or i["Artista"] == MyData[0].title():379                    self.search = controller_mostra_search(MyData)380                    self.check_mostra_search = True381                    var_search = True382                    self.search.show()383                    break384        else:   self.pop_message(text="Immetti il nome di un brano, di un album o di un artista.")385        if not var_search and MyData[0]:386            self.pop_message(text="Non ho trovato nessun risultato.")387    """Controlle Logout"""388    def show_logout(self):389        self.pop_message(text="Arrivederci")390        if self.check_verifica_etichetta is True:391            self.etichetta.close()392            self.check_verifica_etichetta = False393        if self.check_login_page is True:394            self.login.close()395            self.check_login_page = False396        if self.check_newuser_page is True:397            self.newuser.close()398            self.check_newuser_page = False399        if self.check_home_ascoltatore is True:400            self.ascoltatore.close()401            self.check_home_ascoltatore = False402        if self.check_home_artista is True:403            self.artista.close()404            self.check_home_artista = False405        if self.check_home_etichetta is True:406            self.etichetta.close()407            self.check_home_etichetta = False408        if self.check_home_etichetta is True:409            self.etichetta.close()410            self.check_home_etichetta = False411        if self.check_impostazioni_ascoltatore is True:412            self.impostazioni_ascoltatore.close()413            self.check_impostazioni_ascoltatore = False414        if self.check_edit_ascoltatore is True:415            self.EditAscoltatore.close()416            self.check_edit_ascoltatore = False417        if self.check_impostazioni_artista is True:418            self.impostazioni_artista.close()419            self.check_impostazioni_artista = False420        if self.check_edit_artista is True:421            self.EditArtista.close()422            self.check_edit_artista = False423        if self.check_impostazioni_etichetta is True:424            self.impostazioni_etichetta.close()425            self.check_impostazioni_etichetta = False426        if self.check_conferma_credenziali is True:427            self.conferma_credenziali.close()428            self.check_conferma_credenziali= False429        if self.check_conferma_edit is True:430            self.conferma_edit.close()431            self.check_conferma_edit = False432        if self.check_mostra_tutto is True:433            pygame.mixer.init()434            self.player.close()435            self.check_mostra_tutto = False436        if self.check_mostra_search is True:437            pygame.mixer.init()438            self.search.close()439            self.check_mostra_search= False440        if self.check_easter_egg is True:441            self.easter.close()442            self.check_easter_egg = False443        if self.check_rimozione_brani is True:444            self.controlla_eliminazione.close()445            self.check_rimozione_brani = False446        if self.check_scelta_rimozione_brano is True:447            self.rimuovi.close()448            self.check_scelta_rimozione_brano = False449        if self.check_richiesta_nBrani1 is True:450            self.Richiesta_nBrani.close()451            self.check_richiesta_nBrani1= False452        if self.check_pubblicazione_brano_artista is True:453            self.Caricamento_Brano_Artista.close()454            self.check_pubblicazione_brano_artista = False455        if self.check_pubblicazione_brano_etichetta1 is True:456            self.Caricamento_Brano_etichetta.close()457            self.check_pubblicazione_brano_etichetta1 = False458        if self.check_pubblicazione_inizio1 is True:459            self.pubblicazione_inizio.close()460            self.check_pubblicazione_inizio1 = False461        if self.check_login_page is False:462            self.show_login_page()463    def statistica_top5(self):464        self.g = Gestione_json()465        json_data = self.g.get_jsonobject()466        controller_top = TopFive()467        sort_conta = controller_top.sort_lista_contatori(json_data)468        Titoli_top5 = []469        for i in sort_conta:470            for j in json_data:471                if i==j["contatore"]:472                    Titoli_top5.append(j["Titolo"])473                    break474        return Titoli_top5475    def statistica_mie_brani_artista(self):476        self.data = DataPick()477        json_data = self.g.get_jsonobject()478        brani_artista = []479        nome_artista = self.data.return_credenziali()[1].title()+" "+self.data.return_credenziali()[2].title()480        for i in json_data:481            if nome_artista == i["Artista"]:482                brani_artista.append(i["Titolo"])483        return brani_artista484def main():485    app = QtWidgets.QApplication(sys.argv)486    controller = Controller()487    controller.show_login_page()488    sys.exit(app.exec_())489if __name__ == "__main__":...app.py
Source:app.py  
1from flask import Flask, render_template, flash, redirect, url_for, session, logging, request, jsonify, make_response2from flask_mysqldb import MySQL3from passlib.hash import sha256_crypt4from functools import wraps5from flask_mail import Mail, Message6from authlib.integrations.flask_client import OAuth7from flask_restful import Api8from flask_jwt_extended import (JWTManager, jwt_required,9                                jwt_refresh_token_required,10                                jwt_optional, fresh_jwt_required,11                                get_raw_jwt, get_jwt_identity,12                                create_access_token, create_refresh_token,13                                set_access_cookies, set_refresh_cookies,14                                unset_jwt_cookies, unset_access_cookies)15from datetime import timedelta16import string17import random18import math19import uuid20import os21LETTERS = string.ascii_letters22NUMBERS = string.digits23PUNCTUATION = string.punctuation24#os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'25app = Flask(__name__, static_url_path='/static')26# Secret key Config27app.config['SECRET_KEY'] = "mysupersecretkeymysupersecretkeymysupersecretkey"28app.config['BASE_URL'] = 'http://127.0.0.1:5000'  # Running on localhost29app.config['JWT_TOKEN_LOCATION'] = ['cookies']30app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)31app.config['JWT_COOKIE_CSRF_PROTECT'] = True32app.config['JWT_CSRF_CHECK_FORM'] = True33app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'34app.config['JWT_ACCESS_COOKIE_PATH'] = ['/dashboard', '/']35app.config['PROPAGATE_EXCEPTIONS'] = True36# MySql Config37app.config["MYSQL_HOST"] = "localhost"38app.config["MYSQL_USER"] = "root"39app.config["MYSQL_PASSWORD"] = ""40app.config["MYSQL_DB"] = "dbname"41app.config["MYSQL_CURSORCLASS"] = "DictCursor"42app.config["FLASK_HTPASSWD_PATH"] = '/secret/.htpasswd'43# Mail Config44app.config["MAIL_SERVER"] = "xxx.xxx.com"45app.config["MAIL_PORT"] = 46546app.config["MAIL_USE_SSL"] = True47app.config["MAIL_USE_TLS"] = False48app.config["MAIL_USERNAME"] = "xxx@xxx.com"49app.config["MAIL_PASSWORD"] = 'xxxxxxxx'50# Sing in With Config51app.config['GOOGLE_CLIENT_ID'] = "xxx"52app.config['GOOGLE_CLIENT_SECRET'] = "xxx"53app.config['GITHUB_CLIENT_ID'] = "xxx"54app.config['GITHUB_CLIENT_SECRET'] = "xxx"55mysql = MySQL(app)56mail = Mail(app)57oauth = OAuth(app)58jwt = JWTManager(app)59Global_HaveToLogin = False60Check_Login_page = False61PostFail = False62SeccionLog = False63Resetfail = False64ResetHavetoBool = False65@jwt.unauthorized_loader66def unauthorized_callback(callback):67    # No auth header68    flash(message="You must be logged in.", category="danger")69    global Check_Login_page70    global ResetHavetoBool71    Check_Login_page = True72    ResetHavetoBool = True73    return redirect(url_for('index', HaveToLogin=Check_Login_page))74@jwt.invalid_token_loader75def invalid_token_callback(callback):76    # Invalid Fresh/Non-Fresh Access token in auth header77    flash(message="You must be logged in.", category="danger")78    global Check_Login_page79    global ResetHavetoBool80    Check_Login_page = True81    ResetHavetoBool = True82    resp = make_response(83        redirect(url_for('index', HaveToLogin=Check_Login_page)))84    unset_jwt_cookies(resp)85    return resp, 30286@jwt.expired_token_loader87def expired_token_callback(callback):88    # Expired auth header89    resp = make_response(redirect(app.config['BASE_URL'] + '/token/refresh'))90    unset_access_cookies(resp)91    return resp, 30292@app.route('/token/refresh', methods=['GET'])93@jwt_refresh_token_required94def refresh():95    # Refreshing expired Access token96    user_id = get_jwt_identity()97    access_token = create_access_token(identity=str(user_id))98    resp = make_response(redirect(app.config['BASE_URL'] + '/', 302))99    set_access_cookies(resp, access_token)100    return resp101def assign_access_refresh_tokens(user_id, url):102    access_token = create_access_token(identity=str(user_id), fresh=True)103    refresh_token = create_refresh_token(identity=str(user_id))104    resp = make_response(redirect(url, 302))105    set_access_cookies(resp, access_token)106    set_refresh_cookies(resp, refresh_token)107    return resp108def unset_jwt():109    resp = make_response(redirect(app.config['BASE_URL'] + '/', 302))110    unset_jwt_cookies(resp)111    return resp112@app.route("/", methods=['GET', 'POST'])113@jwt_optional114def index():115    username = get_jwt_identity()116    if username != None:117        return redirect(url_for('dashboard'))118    if(request.method == "POST"):119        return PostMessage()120    else:121        return GetMessage()122def PostMessage():123    if(request.form['LoginId'] == "1"):124        return logindef()125    elif(request.form['LoginId'] == "2"):126        return registerdef()127    else:128        return Forgetdef()129def GetMessage():130    global Global_HaveToLogin131    global Check_Login_page132    global PostFail133    global Resetfail134    global ResetHavetoBool135    title = "From data to game experience"136    Check_Login_page = False137    PostFail = False138    Resetfail = False139    if(ResetHavetoBool):140        ResetHavetoBool = False141        Global_HaveToLogin = True142    else:143        Global_HaveToLogin = False144    return render_template("index.html", title=title, Resetfail=Resetfail, HaveToLogin=Global_HaveToLogin, PostFail=PostFail)145def registerdef():146    global PostFail147    global SeccionLog148    companyname = request.form['CompanyName']149    email = request.form['Email']150    password = sha256_crypt.encrypt(request.form['Password'])151    cursor = mysql.connection.cursor()152    Fsorgu = " SELECT * FROM users WHERE email = %s"153    result = cursor.execute(Fsorgu, (email,))154    if(result > 0):155        flash(message="This user already exists!", category="warning")156        PostFail = True157        return render_template("index.html", PostFail=PostFail)158    else:159        Rsorgu = "INSERT INTO users (companyname,email,password,customerid,token) VALUES(%s,%s,%s,%s,%s)"160        customerid = RandomNumber(64)161        forgetPassToken = RandomNumber(64)162        # ,createcustomerid(),createtoken()))163        cursor.execute(Rsorgu, (companyname, email, password,164                                customerid, forgetPassToken))165        mysql.connection.commit()166        cursor.close()167        flash(message="The registration was successful ...", category="success")168        PostFail = False169        return assign_access_refresh_tokens(customerid, app.config['BASE_URL'] + '/dashboard')170def logindef():171    global Check_Login_page172    global SeccionLog173    global ResetHavetoBool174    email = request.form['Email']175    entered_password = request.form['Password']176    cursor = mysql.connection.cursor()177    Lsorgu = " SELECT * FROM users WHERE email = %s "178    result = cursor.execute(Lsorgu, (email,))179    if(result > 0):180        data = cursor.fetchone()181        ınDbPasw = data["password"]182        if sha256_crypt.verify(entered_password, ınDbPasw):183            flash(message="The login was successful...", category="success")184            return assign_access_refresh_tokens(data["customerid"], app.config['BASE_URL'] + '/dashboard')185        else:186            ResetHavetoBool = True187            flash(message="Username or password is wrong.", category="danger")188            Check_Login_page = True189            return render_template("index.html", HaveToLogin=Check_Login_page)190    else:191        flash(message="There is no such user.", category="danger")192        Check_Login_page = True193        return render_template("index.html", HaveToLogin=Check_Login_page)194def Forgetdef():195    global Resetfail196    global Check_Login_page197    global ResetHavetoBool198    email = request.form['Email']199    token = str(uuid.uuid4())200    cursor = mysql.connection.cursor()201    Fsorgu = " SELECT * FROM users WHERE email = %s"202    result = cursor.execute(Fsorgu, (email,))203    if(result > 0):204        data = cursor.fetchone()205        msg = Message(subject="Forgot password request ",206                      sender="resetmail@appneuron.com", recipients=[email])207        msg.html = render_template("MailTemplate.html", token=token, data=data)208        mail.send(msg)209        cursor = mysql.connection.cursor()210        Fsorgu = "UPDATE users SET token =%s WHERE email=%s"211        result = cursor.execute(Fsorgu, (token, email))212        mysql.connection.commit()213        cursor.close()214        flash(message="The password reset link has been sent to your e-mail.",215              category="success")216        ResetHavetoBool = True217        Check_Login_page = True218        return render_template("index.html", HaveToLogin=Check_Login_page)219    else:220        Resetfail = True221        flash(message="The e-mail not exist", category="danger")222        return render_template("index.html", Resetfail=Resetfail)223@app.route("/reset/<token>", methods=['GET', 'POST'])224def reset(token):225    global Check_Login_page226    global ResetHavetoBool227    if(request.method == "POST"):228        password = sha256_crypt.encrypt(request.form['password'])229        token1 = str(uuid.uuid4())230        cursor = mysql.connection.cursor()231        ResetSorgu = "SELECT * FROM users WHERE token =%s"232        cursor.execute(ResetSorgu, (token,))233        user = cursor.fetchone()234        if user:235            cursor = mysql.connection.cursor()236            Fsorgu = "UPDATE users SET token=%s, password=%s Where token=%s"237            cursor.execute(Fsorgu, (token1, password, token))238            mysql.connection.commit()239            cursor.close()240            flash(message="Your password successfuly updated", category="success")241            Check_Login_page = True242            ResetHavetoBool = True243            return redirect(url_for('index', HaveToLogin=Check_Login_page))244        else:245            flash(message="Your token is invalid", category="danger")246            Check_Login_page = True247            ResetHavetoBool = True248            return redirect(url_for('index', HaveToLogin=Check_Login_page))249    else:250        return render_template("reset.html")251############################# Sing in With #######################################252google = oauth.register(253    name='google',254    client_id=app.config["GOOGLE_CLIENT_ID"],255    client_secret=app.config["GOOGLE_CLIENT_SECRET"],256    access_token_url='https://accounts.google.com/o/oauth2/token',257    access_token_params=None,258    authorize_url='https://accounts.google.com/o/oauth2/auth',259    authorize_params=None,260    api_base_url='https://www.googleapis.com/oauth2/v1/',261    # This is only needed if using openId to fetch user info262    userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo',263    client_kwargs={'scope': 'openid email profile'},264)265# Google login route266@app.route('/login/google')267def google_login():268    google = oauth.create_client('google')269    redirect_uri = url_for('google_authorize', _external=True)270    return google.authorize_redirect(redirect_uri)271# Google authorize route272@app.route('/login/google/authorize')273def google_authorize():274    global Check_Login_page275    global SeccionLog276    global ResetHavetoBool277    global PostFail278    google = oauth.create_client('google')279    googletoken = google.authorize_access_token()280    print(googletoken)281    resp = google.get('userinfo').json()282    if resp["id"] != "":283        cursor = mysql.connection.cursor()284        Fsorgu = " SELECT * FROM users WHERE email = %s"285        result = cursor.execute(Fsorgu, (resp["email"],))286        if(result > 0):287            data = cursor.fetchone()288            PostFail = False289            return assign_access_refresh_tokens(data["customerid"], app.config['BASE_URL'] + '/dashboard')290        else:291            Rsorgu = "INSERT INTO users (companyname,email,password,customerid,token) VALUES(%s,%s,%s,%s,%s)"292            customerid = RandomNumber(64)293            forgetPassToken = RandomNumber(64)294            password = sha256_crypt.encrypt(RandomNumber(64))295            cursor.execute(Rsorgu, (resp["name"].replace(296                " ", ""), resp["email"], password, customerid, forgetPassToken))297            mysql.connection.commit()298            cursor.close()299            flash(message="The registration was successful ...", category="success")300            PostFail = False301            return assign_access_refresh_tokens(customerid, app.config['BASE_URL'] + '/dashboard')302    else:303        flash(message="something went wrong. Please try again later!",304              category="danger")305        Check_Login_page = True306        ResetHavetoBool = True307        return redirect(url_for('index', HaveToLogin=Check_Login_page))308###########################################################################309@app.route('/logout')310@jwt_required311def logout():312    return unset_jwt(), 302313@app.route("/dashboard", methods=['GET', 'POST'])314@fresh_jwt_required315def dashboard():316    return render_template("dashboard.html")317@app.route("/terms")318def TermAndCondition():319    return render_template("TermAndCondition.html")320def RandomNumber(length):321    printable = f'{LETTERS}{NUMBERS}{PUNCTUATION}'322    # convert printable from string to list and shuffle323    printable = list(printable)324    random.shuffle(printable)325    # generate random password and convert to string326    random_password = random.choices(printable, k=length)327    random_password = ''.join(random_password)328    return random_password329if __name__ == "__main__":...test_login.py
Source:test_login.py  
...42    @pytest.mark.Login43    def test_case_1(self, setup):44        time.sleep(3)45        lp = LoginPage(self.driver)46        lp.check_login_page()47        ap = AccountOverviewPage(self.driver)48        if lp.login_to_spotify(self.correct_emails[0], self.correct_passwords[0]):49            ap.click_logout()50            WebHelper().report_allure("SUCCESS: Login succeeded with correct credentials", self.driver)51            assert True52        else:53            WebHelper().report_allure("ERROR: Login failed with correct credentials", self.driver)54            assert False55    # Test #2 ->Correct credentials56    @allure.severity(allure.severity_level.BLOCKER)57    @allure.story("Passing login")58    @allure.sub_suite("Login with correct credentials")59    @allure.title("Login with correct credentials")60    @allure.description("Signing in with the following credentials email : test1@test.com & password: test123")61    @pytest.mark.Do62    @pytest.mark.Login63    def test_case_2(self, setup):64        time.sleep(3)65        lp = LoginPage(self.driver)66        lp.check_login_page()67        ap = AccountOverviewPage(self.driver)68        if lp.login_to_spotify(self.correct_emails[1], self.correct_passwords[1]):69            ap.click_logout()70            WebHelper().report_allure("SUCCESS: Login succeeded with correct credentials", self.driver)71            assert True72        else:73            WebHelper().report_allure("ERROR: Login failed with correct credentials", self.driver)74            assert False75    # Test #3 ->Correct credentials76    @allure.severity(allure.severity_level.BLOCKER)77    @allure.story("Passing login")78    @allure.sub_suite("Login with correct credentials")79    @allure.title("Login with correct credentials")80    @allure.description("Signing in with the following credentials email : test1@test.com & password: test123")81    @pytest.mark.Do82    @pytest.mark.Login83    def test_case_3(self, setup):84        time.sleep(3)85        lp = LoginPage(self.driver)86        lp.check_login_page()87        ap = AccountOverviewPage(self.driver)88        if lp.login_to_spotify(self.correct_emails[2], self.correct_passwords[2]):89            ap.click_logout()90            WebHelper().report_allure("SUCCESS: Login succeeded with correct credentials", self.driver)91            assert True92        else:93            WebHelper().report_allure("ERROR: Login failed with correct credentials", self.driver)94            assert False95    # Test #4 ->Wrong Password96    @allure.severity(allure.severity_level.BLOCKER)97    @allure.story("Failing login")98    @allure.sub_suite("Login with wrong password")99    @allure.title("Login with wrong password")100    @allure.description(101        "Signing in with the following credentials email : kamelmohsenkamel@gmail.com & password: wrong password")102    @pytest.mark.Do103    @pytest.mark.Login104    def test_case_4(self, setup):105        time.sleep(3)106        lp = LoginPage(self.driver)107        lp.check_login_page()108        ap = AccountOverviewPage(self.driver)109        if lp.login_to_spotify("kamelmohsenkamel@gmail.com", "wrong_password"):110            ap.click_logout()111            WebHelper().report_allure("ERROR: Login succeeded with incorrect credentials", self.driver)112            assert False113        else:114            WebHelper().report_allure("SUCCESS: Login failed with incorrect credentials", self.driver)115            assert True116    # Test #5 ->Wrong Email117    @allure.severity(allure.severity_level.BLOCKER)118    @allure.story("Failing login")119    @allure.sub_suite("Login with wrong email")120    @allure.title("Login with wrong email")121    @allure.description("Signing in with the following credentials email : kamelmohsenkamel & password: Kimo2010")122    @pytest.mark.Do123    @pytest.mark.Login124    def test_case_5(self, setup):125        time.sleep(3)126        lp = LoginPage(self.driver)127        lp.check_login_page()128        ap = AccountOverviewPage(self.driver)129        if lp.login_to_spotify("kamelmohsenkamel", "Kimo2010"):130            ap.click_logout()131            WebHelper().report_allure("ERROR: Login succeeded with incorrect credentials", self.driver)132            assert False133        else:134            WebHelper().report_allure("SUCCESS: Login failed with incorrect credentials", self.driver)135            assert True136    # Test #6 ->Wrong Email and password137    @allure.severity(allure.severity_level.BLOCKER)138    @allure.story("Failing login")139    @allure.sub_suite("Login with wrong email")140    @allure.title("Login with wrong email")141    @allure.description("Signing in with the following credentials email : kamelmohsenkamel & password: Kimo2010")142    @pytest.mark.Do143    @pytest.mark.Login144    def test_case_6(self, setup):145        time.sleep(3)146        lp = LoginPage(self.driver)147        lp.check_login_page()148        ap = AccountOverviewPage(self.driver)149        if lp.login_to_spotify("test_wrong@email.com", "UnknownPassowrd"):150            ap.click_logout()151            WebHelper().report_allure("ERROR: Login succeeded with incorrect credentials", self.driver)152            assert False153        else:154            WebHelper().report_allure("SUCCESS: Login failed with incorrect credentials", self.driver)155            assert True156    # Test #7 ->Empty Email157    @allure.severity(allure.severity_level.BLOCKER)158    @allure.story("Failing login")159    @allure.sub_suite("Login with empty email")160    @allure.title("Login with empty email")161    @allure.description("Signing in with empty email")162    @pytest.mark.Do163    @pytest.mark.Login164    def test_case_7(self, setup):165        time.sleep(3)166        lp = LoginPage(self.driver)167        lp.check_login_page()168        ap = AccountOverviewPage(self.driver)169        if lp.login_to_spotify("", "Kimo2010"):170            ap.click_logout()171            WebHelper().report_allure("ERROR: Login succeeded with empty email", self.driver)172            assert False173        else:174            WebHelper().report_allure("SUCCESS: Login failed with empty email", self.driver)175            assert True176    # Test #8 ->Empty Password177    @allure.severity(allure.severity_level.BLOCKER)178    @allure.story("Failing login")179    @allure.sub_suite("Login with empty password")180    @allure.title("Login with empty password")181    @allure.description("Signing in with empty password")182    @pytest.mark.Do183    @pytest.mark.Login184    def test_case_8(self, setup):185        time.sleep(3)186        lp = LoginPage(self.driver)187        lp.check_login_page()188        ap = AccountOverviewPage(self.driver)189        if lp.login_to_spotify("mohdos_1999@hotmail.com", ""):190            ap.click_logout()191            WebHelper().report_allure("ERROR: Login succeeded with empty password", self.driver)192            assert False193        else:194            WebHelper().report_allure("SUCCESS: Login failed with empty password", self.driver)195            assert True196    # Test #9 ->Empty Email and Password197    @allure.severity(allure.severity_level.BLOCKER)198    @allure.story("Failing login")199    @allure.sub_suite("Login with empty email and password")200    @allure.title("Login with empty email and password")201    @allure.description("Signing in with empty email and password")202    @pytest.mark.Do203    @pytest.mark.Login204    def test_case_9(self, setup):205        time.sleep(3)206        lp = LoginPage(self.driver)207        lp.check_login_page()208        ap = AccountOverviewPage(self.driver)209        if lp.login_to_spotify("", ""):210            ap.click_logout()211            WebHelper().report_allure("ERROR: Login succeeded with empty email and password", self.driver)212            assert False213        else:214            WebHelper().report_allure("SUCCESS: Login failed with empty email and password", self.driver)215            assert True216    # Test #10 -> Testing Refresh217    @allure.severity(allure.severity_level.BLOCKER)218    @allure.story("Refresh Page test")219    @allure.sub_suite("Refresh Page test")220    @allure.title("Refresh Page test")221    @allure.description("Testing to refresh page that elements are still available")...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
