Package spade :: Module content
[hide private]
[frames] | no frames]

Source Code for Module spade.content

  1  # encoding: UTF-8 
  2  from xmpp import simplexml 
  3  from exceptions import KeyError 
  4   
5 -def co2xml(map):
6 """ Convenience recursive function for transforming ContentObjects into XML. 7 The transformation is {x:y} --> <x>y</x> """ 8 xml = "" 9 for key, value in map.items(): 10 if "ContentObject" in str(type(value)): 11 xml += "<%s>%s</%s>" % (key, co2xml(value), key) 12 elif "list" in str(type(value)): 13 xml += '<%s list="true">' % (key) 14 for i in value: 15 xml += "<%s>%s</%s>" % (key, i, key) 16 xml += "</%s>" % (key) 17 elif value != None and value != "None": 18 xml += "<%s>%s</%s>" % (key, value, key) 19 return xml
20
21 -class ContentObject(dict):
22 """ 23 WARNING: copy.copy() does NOT work for this class :-? 24 """
25 - def __init__(self, namespaces={}):
26 dict.__init__(self) 27 self.namespaces = namespaces
28
29 - def __setitem__(self, key, value):
30 #print "KEY: ", key, "VALUE: ", value 31 try: 32 if ":" in key: 33 prefix,tag = key.rsplit(":") 34 if prefix not in self.namespaces: 35 # The usual FIPA namespace 36 if prefix == "fipa": 37 self.addNamespace("http://www.fipa.org/schemas/fipa-rdf0#", "fipa") 38 else: 39 self.addNamespace("",prefix) 40 except: 41 pass 42 return dict.__setitem__(self, key, value)
43 44
45 - def DEACTIVATED__setattr__(self, key, value):
46 """ 47 Overloader of __setattr__ allows for entering keys in prefix:tag format 48 without worry. 49 """ 50 #print "KEY: ", key, "VALUE: ", value 51 if not self.__dict__.has_key('_ContentObject__initialised'): 52 return dict.__setattr__(self, key, value) 53 elif self.__dict__.has_key(key): 54 dict.__setattr__(self, key, value) 55 else: 56 #self.__setitem__(key, value) 57 try: 58 if ":" in key: 59 prefix,tag = key.rsplit(":") 60 if prefix not in self.namespaces: 61 # The usual FIPA namespace 62 if prefix == "fipa": 63 self.addNamespace("http://www.fipa.org/schemas/fipa-rdf0#", "fipa") 64 else: 65 self.addNamespace("",prefix) 66 except: 67 pass 68 self.__setitem__(key, value)
69 70
71 - def __getattr__(self, name):
72 #print "GETATTR:", name 73 try: 74 if self.has_key(name): 75 return self[name] 76 except: 77 pass 78 for ns in self.namespaces.values(): 79 try: 80 if self.has_key(ns+name): 81 return self[ns+name] 82 except: 83 pass 84 # Ethical dilemma: Should ContentObject return a None when trying to 85 # access a key that does not exist or should it raise an Exception? 86 #raise KeyError 87 return None
88
89 - def addNamespace(self, uri, abv):
90 if abv[-1] != ":": 91 abv = abv + ":" 92 self.namespaces[uri] = abv 93 return
94
95 - def pprint(self, ind=0):
96 s = "" 97 for k,v in self.items(): 98 try: 99 s = s + ('\t'*ind)+str(k)+":\n"+v.pprint(ind+1) + '\n' 100 except: 101 s = s + ('\t'*ind)+str(k)+": " + str(v) + '\n' 102 return s
103
104 - def asRDFXML(self):
105 # Build rdf:RDF node 106 root = simplexml.Node("rdf:RDF", {"xmlns:rdf":"http://www.w3.org/1999/02/22-rdf-syntax-ns#"}) 107 nss = {} 108 for k,v in self.namespaces.items(): 109 if v in ["xml:","rdf:"]: 110 pass 111 elif v != None and v != "None": 112 nss["xmlns:"+v[:-1]] = k 113 root.attrs.update(nss) 114 root.addData("#WILDCARD#") 115 return str(root).replace("#WILDCARD#",co2xml(self))
116 117 118 """CAWEN DIOS!!! 119 def asSL0(self): 120 return toSL0(self) 121 122 def toSL0(self, data = None): 123 124 self.co = [] 125 self.l = [] 126 self.other = [] 127 128 sl = "" 129 130 for key,value in data.items(): 131 if "ContentObject" in str(type(value)): self.co.append((key,value)) 132 elif "list" in str(type(value)): self.l.append((key,value)) 133 else self.other.append((key,value)) 134 135 136 137 138 139 140 for key,value in data.items(): 141 if ":" in key: key = key.split(":")[1] 142 143 if "ContentObject" in str(type(value)): 144 sl += "(%s %s )" % (key, toSL0(value)) 145 elif "list" in str(type(value)): 146 sl += "(sequence " 147 for i in value: 148 sl += "(%s %s)" % (key, toSL0(i)) 149 sl += ")" 150 elif value != None and value != "None": 151 sl += " :%s %s " % (key, value) 152 153 154 return sl 155 """ 156
157 - def __str__(self):
158 return co2xml(self)
159 #return self.asRDFXML() 160 161
162 -def Node2CO(node, nsdict):
163 #print "NODE2CO: ",str(node) 164 if len(node.kids) == 0: 165 # Leaf node 166 if node.getData(): 167 return str(node.getData()) 168 else: 169 try: 170 return str(node.attrs["rdf:resource"]) 171 except: 172 return "" 173 else: 174 # Blank node 175 is_list = False 176 # Is it a list? 177 if node.attrs.has_key("list"): 178 # It IS a marked list 179 is_list = True 180 else: 181 for c in node.kids[1:]: 182 if node.kids[0].name == c.name: 183 # It IS a f*ck*ng list!!! 184 is_list = True 185 break 186 if is_list: 187 s = [] 188 for c in node.kids: 189 s.append(Node2CO(c,nsdict)) 190 else: 191 s = ContentObject() 192 for c in node.kids: 193 #print "KID ",c.name," NS ",c.namespace 194 if c.namespace in nsdict.keys(): 195 key = nsdict[c.namespace]+c.name 196 else: 197 key = c.name 198 s[key] = Node2CO(c,nsdict) 199 return s
200 201
202 -def RDFXML2CO(rdfdata):
203 #print "Gonna parse: "+rdfdata 204 nb = simplexml.NodeBuilder(rdfdata) 205 #print "Parsed: "+str(nb.getDom())+str(nb.namespaces) 206 co = Node2CO(nb.getDom(), nb.namespaces) 207 co.namespaces.update(nb.namespaces) 208 return co
209 210 211 if __name__=="__main__": 212 import urllib2 213 #f = urllib2.urlopen("http://infomesh.net/2003/rdfparser/meta.rdf") 214 #f = urllib2.urlopen("http://tourism.gti-ia.dsic.upv.es/rdf/ComidasTascaRapida.rdf") 215 216 ex = """<rdf:RDF 217 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 218 xmlns:foaf="http://xmlns.com/foaf/0.1/" 219 xmlns:dc="http://purl.org/dc/elements/1.1/"> 220 <rdf:Description rdf:about="http://en.wikipedia.org/wiki/Tony_Benn"> 221 <dc:title>Tony Benn</dc:title> 222 <dc:publisher>Wikipedia</dc:publisher> 223 <foaf:primaryTopic> 224 <foaf:Person> 225 <foaf:name>Tony Benn</foaf:name> 226 </foaf:Person> 227 </foaf:primaryTopic> 228 </rdf:Description> 229 <rdf:bla> 230 <rdf:friend>Alice</rdf:friend> 231 <rdf:friend>Bob</rdf:friend> 232 </rdf:bla> 233 </rdf:RDF> 234 """ 235 236 #sco = RDFXML2CO(f.read()) 237 sco = RDFXML2CO(ex) 238 sco.addNamespace("http://spade2.googlecode.com/ns/2.0/", "spade:") 239 sco["rdf:Description"]["foaf:primaryTopic"]["spade:friend"] = [] 240 sco["rdf:Description"]["foaf:primaryTopic"]["spade:friend"].append("John Doe") 241 sco["rdf:Description"]["foaf:primaryTopic"]["spade:friend"].append("Chuck Bartowski") 242 sco["rdf:Description"]["foaf:primaryTopic"]["spade:friend"].append("Sarah Connor") 243 sco["spade:uno"] = ContentObject() 244 sco["spade:uno"]["spade:dos"] = "COSA" 245 sco.uno["spade:tres"] = "OTRA" 246 247 #print str(sco) 248 print "ORIGINAL:" 249 print sco.pprint() 250 #print sco["rdf:Description"]["dc:creator"]["foaf:name"], str(type(sco["rdf:Description"]["dc:creator"]["foaf:name"])) 251 #print sco["rdf:Description"]["dc:creator"]["foaf:homePage"] 252 print sco.asRDFXML() 253 sco2 = RDFXML2CO(sco.asRDFXML()) 254 print "SEGUNDO:" 255 print sco2.pprint() 256 print sco2.asRDFXML() 257 258 #print sco2.asSL0() 259