Skip to content

Instantly share code, notes, and snippets.

@salvaom
Created September 27, 2019 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salvaom/c6df5b39d3a94667c19da20c4d223888 to your computer and use it in GitHub Desktop.
Save salvaom/c6df5b39d3a94667c19da20c4d223888 to your computer and use it in GitHub Desktop.
from six.moves import queue as thqueue
import json
from Qt import QtCore
class DataRetrievalThread(QtCore.QThread):
failed = QtCore.Signal(object)
dataReady = QtCore.Signal(object)
def __init__(self, job_queue=None, parent=None):
super(DataRetrievalThread, self).__init__(parent=None)
self.job_queue = job_queue or thqueue.Queue()
def run(self):
while not self.job_queue.empty():
try:
self.run_next_job()
except Exception as e:
self.failed.emit(str(e))
finally:
self.job_queue.task_done()
def run_next_job(self):
next_ = json.loads(self.job_queue.get())
action = next_['action']
data = next_['data']
response = next_.copy()
if action == 'action1':
self.do_action1(data=data, response=response)
if action == 'action2':
self.do_action2(data=data, response=response)
if action == 'action3':
self.do_action3(data=data, response=response)
if action == 'action3':
self.do_action3(data=data, response=response)
else:
raise NotImplementedError('Action "{}" not implemented'
.format(action))
self.dataReady.emit(json.dumps(response))
def requestData(self, action, data, callback=None):
event = {'id': str(uuid.uuid4()),
'data': data,
'action': action,
'callback': callback,
'source': self._name}
self.events[event['id']] = event
serialized_event = event.copy()
serialized_event.pop('callback')
self.thread_queue.put(json.dumps(serialized_event))
if not self.thread.isRunning() and self.thread_ready:
self.thread.start()
return event['id']
def onThreadJobFinished(self, event):
if event['source'] != self._name:
return
orig_event = self.events[event['id']]
if orig_event['callback']:
orig_event['callback'](event)
self.events[event['id']]['result'] = event['result']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment