Выполнения кода после ответа от сервера
Как сделать чтоб код выполнялся лишь после ответа от запроса.Открывается окно с вводом пароля и логина после нажатия на кнопку "войти", выполняется функция clogging. Тут реализовано обновление токена через определенное время. Делается запрос на авторизацию и после если все верно переход на следующее окно.Проблема, в том что если сначала не зашел то будет False и он выходит и потом ввожу нормальные данные, то для него он все еще False и цикл проверки не работает.
main.py
import sys
import time
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow
from PyQt5.uic import loadUi
import sqlite3 as sq
import pandas as pd
import os
import requests as r
from PyQt5.uic.properties import QtGui
from env import Env
from rest_client import RestClient
app = None
widget = None
class Login(QDialog):
def __init__(self, rest_client: RestClient):
super(Login, self).__init__()
loadUi("login.ui", self)
self.singBtn.clicked.connect(self.clogging)
self.infoLabel.hide()
app.aboutToQuit.connect(self.closeEvent)
self._rest_client = rest_client
def closeEvent(self):
print('close Login window')
self._rest_client.log_out_user()
def clogging(self):
elma_user = self.email.text()
elma_password = self.password.text()
try:
# Делается запрос на регистрацию
self._rest_client.auth_user_with_update(elma_user, elma_password)
# цикл проверки ответа если, ошибка то False, если все хорошо то True
while True:
if self._rest_client.is_authenticated():
widget.setCurrentIndex(1)
break
elif self._rest_client.is_authenticated() is False:
break
except Exception as e:
print('Ошибка в кнопке', e)
# self.infoLabel.setText(repr(e))
# self.infoLabel.show()
class MainWindow(QMainWindow):
filename = None
doc = None
def __init__(self, rest_client):
super(MainWindow, self).__init__()
loadUi("mainWindow.ui", self)
self.excelBtn.clicked.connect(self.excelparsing)
self.action.triggered.connect(self.openfile)
self._rest_client = rest_client
app.aboutToQuit.connect(self.closeEvent)
def openfile(self):
print('open file')
filename, _ = QtWidgets.QFileDialog.getOpenFileName(
self,
'Open Excel File ',
"",
"Excel File (*.xlsx)"
)
if filename:
print(filename)
self.filename = filename
def excelparsing(self):
# widget.setCurrentIndex(0)
self.doc = pd.read_excel(f"{self.filename}", usecols="A,C,L")
con = sq.connect("products.db")
cur = con.cursor()
date = pd.DataFrame(self.doc)
date.to_sql("details", con=con, if_exists="append", index=False)
def closeEvent(self):
print('close main window')
self._rest_client.log_out_user()
def main():
config = Env()
rest_client = RestClient(config=config)
global app
global widget
app = QApplication(sys.argv)
mainapp = MainWindow(rest_client=rest_client)
mainWindow = Login(rest_client=rest_client)
widget = QtWidgets.QStackedWidget()
widget.addWidget(mainWindow)
widget.addWidget(mainapp)
widget.setGeometry(500, 250, 400, 300)
widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Файл с запросами
import time
import requests as r
from env import Env
import threading
class RestClient:
def __init__(self, config: Env):
self._api_token = config.elma_app_token
self._http_rest = f"http://{config.rest_address}:{config.rest_port}/API/REST/"
self.__auth_token__: str = ''
self.__session_token__: str = ''
self.__login__ = ''
self.__password__ = ''
self.__auth_token_livetime__ = config.auth_token_livetime
self.__authenticated__ = None
self.__retry_count__ = config.retry_count
def auth_user(self):
if not self.__password__.startswith('"') or not self.__password__.endswith('"'):
password = self.__password__
else:
password = self.__password__.replace(' ', '')
headers = {"ApplicationToken": self._api_token, "Content-Type": "application/json; charset=utf-8"}
session = r.Session()
session.headers = headers
try:
response = session.post(
f"{self._http_rest}/Authorization/LoginWith", params={"username": self.__login__},
data=password
)
print(response.json())
if (response.status_code in [400, 500]):
self.__authenticated__ = False
raise Exception('Ошибка авторизации или неверный пароль')
data = response.json()
self.__auth_token__ = data['AuthToken']
self.__session_token__ = data['SessionToken']
self.__authenticated__ = True
except Exception as e:
self.__authenticated__ = False
print('Ошибка в auth_user', e)
finally:
session.close()
def log_out_user(self):
self.__auth_token__: str = ''
self.__session_token__: str = ''
self.__login__ = ''
self.__password__ = ''
self.__authenticated__ = False
def is_authenticated(self):
return self.__authenticated__
def auth_user_with_update(self, login='', password=''):
self.__login__ = login
self.__password__ = password
data_updater = threading.Thread(target=self.refresh_user_data, name='User token updater')
data_updater.start()
def refresh_user_data(self):
current_retry = 0
while True:
try:
self.auth_user()
current_retry = 0
time.sleep(2)
except Exception as e:
print(e)
current_retry += 1
if current_retry > self.__retry_count__:
current_retry = 0
break
if not self.__authenticated__ and current_retry == 0:
break