Exemplo n.º 1
0
class cURL:
    """ cURL class used in ISup """
    def __init__(self, url, progresshandler=None):
        self.URL = url
        self.cp = pycurl.Curl()
        ## progressbar
        if not progresshandler:
            from progressbar import Percentage, Bar, ETA, FileTransferSpeed, ProgressBar
            
            pyis_widget = ['UPLOAD: ', Percentage(), ' ', Bar(marker='#', left='[', right=']'), ' ', ETA(), ' ', FileTransferSpeed("K")]
            self.pb = ProgressBar(widgets = pyis_widget, maxval = 100)
            self.progresshandler = self._progress
        else:
            self.progresshandler = progresshandler

    def _progress(self, dt, dd, ut, ud):
        current = (ud != 0) and int(ud / ut * 100) or 1
        if not current == self.pb.percentage():
            self.pb.update(current)


    def getJSON(self, POST, progress = True, verbose = False):
        self.cp.setopt(self.cp.POST, 1)
        self.cp.setopt(self.cp.HTTPPOST, POST)
        self.cp.setopt(self.cp.URL, self.URL)

        if progress and self.progresshandler == self._progress:
            self.pb.start()
            self.cp.setopt(self.cp.NOPROGRESS, 0)
            self.cp.setopt(self.cp.PROGRESSFUNCTION, self.progresshandler)
        elif progress and not self.progresshandler == self._progress:
            self.cp.setopt(self.cp.NOPROGRESS, 0)
            self.cp.setopt(self.cp.PROGRESSFUNCTION, self.progresshandler)
        if verbose:
            self.cp.setopt(self.cp.VERBOSE, 1)
            self.cp.setopt(self.cp.DEBUGFUNCTION, self._debug)

        result = StringIO()
        self.cp.setopt(self.cp.WRITEFUNCTION, result.write)
        self.cp.perform()

        if progress and self.progresshandler == self._progress:
            self.pb.finish()

        return result.getvalue()

    def _debug(self, dtype, dmsg):
        sys.stdout.write("PycURL: ({0:d}): {1:>s}".format(dtype, dmsg))