~gilgamezh/encuentro/virtualenvizar

« back to all changes in this revision

Viewing changes to encuentro/utils.py

  • Committer: Facundo Batista
  • Date: 2013-12-08 23:36:06 UTC
  • mfrom: (192.1.1 remove-twisted)
  • Revision ID: facundo@taniquetil.com.ar-20131208233606-tq1yvw2bm6cbdtz6
Removed twisted (kept deferreds through a new dependency).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2013 Facundo Batista
 
2
#
 
3
# This program is free software: you can redistribute it and/or modify it
 
4
# under the terms of the GNU General Public License version 3, as published
 
5
# by the Free Software Foundation.
 
6
#
 
7
# This program is distributed in the hope that it will be useful, but
 
8
# WITHOUT ANY WARRANTY; without even the implied warranties of
 
9
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 
10
# PURPOSE.  See the GNU General Public License for more details.
 
11
#
 
12
# You should have received a copy of the GNU General Public License along
 
13
# with this program.  If not, see <http://www.gnu.org/licenses/>.
 
14
#
 
15
# For further info, check  https://launchpad.net/encuentro
 
16
 
 
17
"""Some useful functions."""
 
18
 
 
19
import defer
 
20
 
 
21
from PyQt4 import QtNetwork, QtCore
 
22
 
 
23
_qt_network_manager = QtNetwork.QNetworkAccessManager()
 
24
 
 
25
 
 
26
def download(url):
 
27
    """Deferredly download an URL, non blocking."""
 
28
    deferred = defer.Deferred()
 
29
 
 
30
    def end():
 
31
        """Send data through the deferred, if wasn't fired before."""
 
32
        data = req.read(req.bytesAvailable())
 
33
        if not deferred.called:
 
34
            deferred.callback(data)
 
35
 
 
36
    request = QtNetwork.QNetworkRequest()
 
37
    request.setUrl(QtCore.QUrl(url))
 
38
 
 
39
    req = _qt_network_manager.get(request)
 
40
    req.error.connect(deferred.errback)
 
41
    req.finished.connect(end)
 
42
 
 
43
    return deferred
 
44
 
 
45
 
 
46
if __name__ == "__main__":
 
47
    import sys
 
48
    app = QtCore.QCoreApplication(sys.argv)
 
49
    url = "http://www.taniquetil.com.ar/facundo/imgs/felu-camagrande.jpg"
 
50
 
 
51
    @defer.inline_callbacks
 
52
    def _download():
 
53
        """Download."""
 
54
        data = yield download(url)
 
55
        print "All done!", len(data), type(data)
 
56
    _download()
 
57
    sys.exit(app.exec_())