|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2012 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing a class to write user agent data files. |
|
8 """ |
|
9 |
|
10 from PyQt4.QtCore import QXmlStreamWriter, QIODevice, QFile |
|
11 |
|
12 |
|
13 class UserAgentWriter(QXmlStreamWriter): |
|
14 """ |
|
15 Class implementing a writer object to generate user agent data files. |
|
16 """ |
|
17 def __init__(self): |
|
18 """ |
|
19 Constructor |
|
20 """ |
|
21 super().__init__() |
|
22 |
|
23 self.setAutoFormatting(True) |
|
24 |
|
25 def write(self, fileNameOrDevice, agents): |
|
26 """ |
|
27 Public method to write a user agent data file. |
|
28 |
|
29 @param fileNameOrDevice name of the file to write (string) |
|
30 or device to write to (QIODevice) |
|
31 @param agents dictionary with user agent data (host as key, agent string as value) |
|
32 """ |
|
33 if isinstance(fileNameOrDevice, QIODevice): |
|
34 f = fileNameOrDevice |
|
35 else: |
|
36 f = QFile(fileNameOrDevice) |
|
37 if not agents or not f.open(QFile.WriteOnly): |
|
38 return False |
|
39 |
|
40 self.setDevice(f) |
|
41 return self.__write(agents) |
|
42 |
|
43 def __write(self, agents): |
|
44 """ |
|
45 Private method to write a user agent file. |
|
46 |
|
47 @param agents dictionary with user agent data (host as key, agent string as value) |
|
48 @return flag indicating success (boolean) |
|
49 """ |
|
50 self.writeStartDocument() |
|
51 self.writeDTD("<!DOCTYPE passwords>") |
|
52 self.writeStartElement("UserAgents") |
|
53 self.writeAttribute("version", "1.0") |
|
54 |
|
55 for host, agent in agents.items(): |
|
56 self.writeEmptyElement("UserAgent") |
|
57 self.writeAttribute("host", host) |
|
58 self.writeAttribute("agent", agent) |
|
59 |
|
60 self.writeEndDocument() |
|
61 return True |