Search code examples
python-3.xpyqtpyqt5pydrive

How to write non blocking code using PyQT5 for uploading to google drive with PyDrive?


I am trying to upload data to Google Drive using pydrive on click of a button of PyQT5. I want to display a message showing like "Data back up in progress...." in status bar (Or onto a label).

However I am getting the message only when uploald is completed. It seems pydrive upload process blocks PyQT process until upload it completed.

How how can I achieved to display the message during the upload process. Below is my code:

def __init__(self, *args, **kwargs):
    super(HomeScreen,self).__init__()
    loadUi('uiScreens/HomeScreen.ui',self)
    self.pushButton.clicked.connect(self.doDataBackup)

def doDataBackup(self):
    dbfile = "mumop.db"     #File to upload
    self.statusBar().showMessage("Data back up in progress....") # This is blocked by pydrive
    print("Data backup is in progress.....")  # This test line is not blocked by pdrive
    upload.uploadToGoogleDrive(dbfile))
    
# This  method is in another file
def uploadToGoogleDrive(file):
    gauth = GoogleAuth()
    gauth.LoadCredentialsFile("upload/mumopcreds.txt")
    if gauth.credentials is None:
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        gauth.Refresh()
    else:
        gauth.Authorize()
    gauth.SaveCredentialsFile("upload/mumopcreds.txt")
    drive = GoogleDrive(gauth)
    file1 = drive.CreateFile()
    file1.SetContentFile(file)
    file1.Upload()

Solution

  • And easy way would be to add QApplication.processEvents() after self.statusBar().showMessage(...). This should take care of all UI updates before blocking the event queue with your google access.

    A more sophisticated way would be to outsource the google access into another thread (see e.g. this tutorial), but maybe this is a bit of an overkill for your usecase.