|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2012 - 2022 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing a class to write user agent data files. |
|
8 """ |
|
9 |
|
10 from PyQt6.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 |
|
32 string as value) |
|
33 @return flag indicating success (boolean) |
|
34 """ |
|
35 if isinstance(fileNameOrDevice, QIODevice): |
|
36 f = fileNameOrDevice |
|
37 else: |
|
38 f = QFile(fileNameOrDevice) |
|
39 if not f.open(QIODevice.OpenModeFlag.WriteOnly): |
|
40 return False |
|
41 |
|
42 self.setDevice(f) |
|
43 return self.__write(agents) |
|
44 |
|
45 def __write(self, agents): |
|
46 """ |
|
47 Private method to write a user agent file. |
|
48 |
|
49 @param agents dictionary with user agent data (host as key, agent |
|
50 string as value) |
|
51 @return flag indicating success (boolean) |
|
52 """ |
|
53 self.writeStartDocument() |
|
54 self.writeDTD("<!DOCTYPE useragents>") |
|
55 self.writeStartElement("UserAgents") |
|
56 self.writeAttribute("version", "1.0") |
|
57 |
|
58 for host, agent in agents.items(): |
|
59 self.writeEmptyElement("UserAgent") |
|
60 self.writeAttribute("host", host) |
|
61 self.writeAttribute("agent", agent) |
|
62 |
|
63 self.writeEndDocument() |
|
64 return True |