Menu

[r343]: / trunk / QNAM.py  Maximize  Restore  History

Download this file

301 lines (264 with data), 11.7 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# -*- coding: utf-8 -*-
from PyQt4 import QtCore
from PyQt4.QtCore import QUrl, QFile, QIODevice, QObject, QThread, QEventLoop
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkCookieJar, QNetworkRequest, QNetworkReply
"""
QNAM library for downloading/uploading data.
Redirections will be handled automatically.
###TODO: Upload methods
###TODO: Be able to do GET and POST (maybe an option in methods)
###TODO: Handle errors
###Examples of usage are available at the end of this file.
"""
guserAgent = "Wget/1.12 (linux-gnu)"
guser = ""
gpassword = ""
"""
This class will download URL and return it like raw data.
Calling download() will block until finished. (synchronous)
Note that for this to work files will be stored in RAM.
Downloading big amount of data this way is certainly a bad idea.
Object will emit downloadProgress(int, int) signal in order
to let you track the progress.
"""
class Sync(QObject):
def download(self, url, userAgent = guserAgent, user = guser, password = gpassword):
self.jar = QNetworkCookieJar()
self.manager = QNetworkAccessManager()
self.manager.setCookieJar(self.jar)
self.manager.finished.connect(self.downloadFinished)
self.manager.authenticationRequired.connect(self.authenticationRequired)
self.url = QUrl(url)
self.userAgent = userAgent
self.user = user
self.password = password
self.returnData = None
self.request = QNetworkRequest(self.url)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.downloadProgress.connect(self.progressCallback)
self.eventloop = QEventLoop()
self.eventloop.exec_()
return self.returnData
def authenticationRequired(self, reply, authenticator):
authenticator.setUser(self.user)
authenticator.setPassword(self.password)
def progressCallback(self, done, total):
self.emit(QtCore.SIGNAL('downloadProgress(int, int)'), done, total)
def downloadFinished(self, reply):
self.redirect = reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl()
if not self.redirect.isEmpty():
self.request = QNetworkRequest(self.redirect)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.downloadProgress.connect(self.progressCallback)
else:
self.returnData = self.reply.readAll()
self.eventloop.quit()
"""
This class will download URL and will write it to disk.
Calling download() will block until finished. (synchoronous)
Note that even if the download() method is syncronous, data
will be writen in asynchronous mode. This way data won't be stored
in RAM avoiding huge RAM usage for big amount of data.
Object will emit downloadProgress(int, int) signal in order
to let you track the progress.
"""
class SyncToFile(QObject):
def download(self, url, path, userAgent = guserAgent, user = guser, password = gpassword):
self.jar = QNetworkCookieJar()
self.manager = QNetworkAccessManager()
self.manager.setCookieJar(self.jar)
self.manager.finished.connect(self.downloadFinished)
self.manager.authenticationRequired.connect(self.authenticationRequired)
self.url = QUrl(url)
self.path = QFile(path)
self.path.open(QIODevice.WriteOnly)
self.userAgent = userAgent
self.user = user
self.password = password
self.request = QNetworkRequest(self.url)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.readyRead.connect(self.readyRead)
self.reply.downloadProgress.connect(self.progressCallback)
self.eventloop = QEventLoop()
self.eventloop.exec_()
return
def authenticationRequired(self, reply, authenticator):
authenticator.setUser(self.user)
authenticator.setPassword(self.password)
def readyRead(self):
self.path.write(self.reply.readAll())
def progressCallback(self, done, total):
self.emit(QtCore.SIGNAL('downloadProgress(int, int)'), done, total)
def downloadFinished(self, reply):
self.redirect = reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl()
if not self.redirect.isEmpty():
self.request = QNetworkRequest(self.redirect)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
try:
self.path.close()
self.path.open(QIODevice.WriteOnly)
except:
pass
self.reply.readyRead.connect(self.readyRead)
self.reply.downloadProgress.connect(self.progressCallback)
else:
self.path.close()
self.eventloop.quit()
"""
This class will download URL and will emit an event with raw data when finished.
Calling download() won't block (asynchronous). Object will emit downloadFinished(PyQt_PyObject)
signal in order to let you know that the download has finished, and to let you
get raw data from reply. Note that for this to work data will be stored in RAM.
Downloading big amount of data this way is certainly a bad idea.
Object will emit downloadProgress(int, int) signal in order
to let you track the progress.
"""
class Async(QThread):
def run(self):
self.jar = QNetworkCookieJar()
self.manager = QNetworkAccessManager()
self.manager.setCookieJar(self.jar)
self.manager.finished.connect(self.downloadFinished)
self.manager.authenticationRequired.connect(self.authenticationRequired)
self.request = QNetworkRequest(self.url)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.downloadProgress.connect(self.progressCallback)
self.exec_()
def download(self, url, userAgent = guserAgent, user = guser, password = gpassword):
self.url = QUrl(url)
self.userAgent = userAgent
self.user = user
self.password = password
self.returnData = None
self.moveToThread(self)
self.start()
def authenticationRequired(self, reply, authenticator):
authenticator.setUser(self.user)
authenticator.setPassword(self.password)
def progressCallback(self, done, total):
self.emit(QtCore.SIGNAL('downloadProgress(int, int)'), done, total)
def downloadFinished(self, reply):
self.redirect = reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl()
if not self.redirect.isEmpty():
self.request = QNetworkRequest(self.redirect)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.downloadProgress.connect(self.progressCallback)
else:
self.emit(QtCore.SIGNAL('downloadFinished(PyQt_PyObject)'), str(self.reply.readAll()))
self.quit()
"""
This class will download URL and will write it to disk.
Calling download() won't block (asynchronous). Object will emit downloadFinished()
signal in order to let you know that the download has finished.
Note that data will be writen in asynchronous mode. This way data
won't be stored in RAM avoiding huge RAM usage for big amount of data.
Object will emit downloadProgress(int, int) signal in order
to let you track the progress.
"""
class AsyncToFile(QThread):
def run(self):
self.jar = QNetworkCookieJar()
self.manager = QNetworkAccessManager()
self.manager.setCookieJar(self.jar)
self.manager.finished.connect(self.downloadFinished)
self.manager.authenticationRequired.connect(self.authenticationRequired)
self.request = QNetworkRequest(self.url)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
self.reply.readyRead.connect(self.readyRead)
self.reply.downloadProgress.connect(self.progressCallback)
self.exec_()
def download(self, url, path, userAgent = guserAgent, user = guser, password = gpassword):
self.url = QUrl(url)
self.path = QFile(path)
self.path.open(QIODevice.WriteOnly)
self.userAgent = userAgent
self.user = user
self.password = password
self.returnData = None
self.moveToThread(self)
self.start()
def authenticationRequired(self, reply, authenticator):
authenticator.setUser(self.user)
authenticator.setPassword(self.password)
def readyRead(self):
self.path.write(self.reply.readAll())
def progressCallback(self, done, total):
self.emit(QtCore.SIGNAL('downloadProgress(int, int)'), done, total)
def downloadFinished(self, reply):
self.redirect = reply.attribute(QNetworkRequest.RedirectionTargetAttribute).toUrl()
if not self.redirect.isEmpty():
self.request = QNetworkRequest(self.redirect)
self.request.setRawHeader("User-Agent", self.userAgent)
self.reply = self.manager.get(self.request)
try:
self.path.close()
self.path.open(QIODevice.WriteOnly)
except:
pass
self.reply.readyRead.connect(self.readyRead)
self.reply.downloadProgress.connect(self.progressCallback)
else:
self.path.close()
self.emit(QtCore.SIGNAL('downloadFinished()'))
self.quit()
###Examples of usage###
"""
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QEventLoop
from QNAM import Sync, SyncToFile, Async, AsyncToFile
class Test():
def syncProgress(self, done, total):
print "\r", "Sync progress: " + str(done) + " of " + str(total),
def syncToFileProgress(self, done, total):
print "\r", "SyncToFile progress: " + str(done) + " of " + str(total),
def asyncProgress(self, done, total):
print "\r", "Async progress: " + str(done) + " of " + str(total),
def asyncToFileProgress(self, done, total):
print "\r", "AsyncToFile progress: " + str(done) + " of " + str(total),
def asyncFinished(self, data):
print "\nAsync finished!"
self.eventloop.quit()
def asyncToFileFinished(self):
print "\nAsyncToFile finished!"
self.eventloop.quit()
def run(self):
self.eventloop = QEventLoop()
print "Sync test..."
self.objsync = Sync()
QtCore.QObject.connect(self.objsync, QtCore.SIGNAL("downloadProgress(int, int)"), self.syncProgress)
self.objsync.download("http://sourceforge.net/projects/python-jake/files/betas/Jake-PyQT4-0.1.zip/download")
print "\nSync finished!"
print "SyncToFile test..."
self.objsynctofile = SyncToFile()
QtCore.QObject.connect(self.objsynctofile, QtCore.SIGNAL("downloadProgress(int, int)"), self.syncToFileProgress)
self.objsynctofile.download("http://sourceforge.net/projects/python-jake/files/betas/Jake-PyQT4-0.1.zip/download", "/tmp/something")
print "\nSyncToFile finished!"
print "Async test..."
self.objasync = Async()
QtCore.QObject.connect(self.objasync, QtCore.SIGNAL("downloadProgress(int, int)"), self.asyncProgress)
QtCore.QObject.connect(self.objasync, QtCore.SIGNAL("downloadFinished(PyQt_PyObject)"), self.asyncFinished)
self.objasync.download("http://sourceforge.net/projects/python-jake/files/betas/Jake-PyQT4-0.1.zip/download")
print "After download() start..."
self.eventloop.exec_()
print "AsyncToFile test..."
self.objasynctofile = AsyncToFile()
QtCore.QObject.connect(self.objasynctofile, QtCore.SIGNAL("downloadProgress(int, int)"), self.asyncToFileProgress)
QtCore.QObject.connect(self.objasynctofile, QtCore.SIGNAL("downloadFinished()"), self.asyncToFileFinished)
self.objasynctofile.download("http://sourceforge.net/projects/python-jake/files/betas/Jake-PyQT4-0.1.zip/download", "/tmp/something")
print "After download() start..."
self.eventloop.exec_()
print "Everything is OK!"
sys.exit(0)
app = QtGui.QApplication(sys.argv)
a = Test()
a.run()
app.exec_()
"""