Riedl's Blog

PyQt5 Network Manager

Published on 03 Jan 2021
Tags: programming

As I was working on the SMRT CLK dashboard, I came across the issue of using the QNetworkAccessManager in PyQt5. The reference code I was working from was written for PyQt4 and it utilized global variables to move data around. I felt that the global variables were probably a workaround for how the manager and request were meant to be handled so I did some searching. I eventually found that this is the correct way to make a QNetworkRequest.

# Create the network manager
manager = QtNetwork.QNetworkAccessManager()
# Attach the weather interface update function
manager.finished.connect(wxupdate)

def get_weather():
    # Create the URL
    url = QUrl('https://api.openweathermap.org/data/2.5/onecall?' +
               'lat=' + lat + '&lon=' + lon + '&units=imperial' +
               '&exclude=minutely,alerts&appid=' + keys.owm_api)
    # Create the network request
    req = QNetworkRequest(url)
    # Get the request
    manager.get(req)
    
def wxupdate(reply):
    if(reply.error() != QNetworkReply.NoError):
        return
    tempstr = str(reply.readAll(), 'utf-8')
    tempdata = json.loads(tempstr)

Another curious thing I came across is that if you accidentally connect multiple functions to the manager by calling connect multiple times, the function will actually be called multiple times. This will result in that function executing with a reply that has an empty payload. This was causing me a ton of issues until I found that was the cause of the function raising an exception.