1. Sergio Fernández
  2. pryoo

Commits

Sergio Fernández  committed 73b95a0

imported from the private repository

  • Participants
  • Branches default

Comments (0)

Files changed (18)

File demo.py

View file
+#!/usr/bin/python
+# -*- coding: utf-8 -
+
+import sys
+import os
+sys.path.append(os.path.abspath(".."))
+
+from pryoo.rdf import RdfResource, RdfProperty
+from pryoo.session import Session
+from pryoo.internals import dump
+
+session = Session("pryoo.yaml")
+
+class Person(RdfResource):
+
+    #name = RdfProperty("foaf:name")
+
+    def __init__(self, name):
+        RdfResource.__init__(self, "foaf:Person")
+        self.name = RdfProperty("foaf:name", name)
+
+    def __str__(self):
+        return "Person: %s" % self.name
+
+if __name__ == "__main__":
+    sergio = Person("sergio")
+    print sergio.name
+    print sergio.rdftype
+    print sergio.get_uri()
+    dump(sergio)
+    #sergio.save()
+    #sergio.delete()
+    #sergio.refresh()
+
+    #Person.find_all()
+
+    wikier = RdfResource.retrieve("http://www.wikier.org/foaf#wikier")
+    dump(wikier)
+    print wikier.foaf_nick
+
+    print wikier.rdfs_comment[0]
+
+    friend = wikier.foaf_knows["http://berrueta.net/foaf.rdf#me"]
+    print friend
+    dump(friend)
+

File exceptions.py

View file
+# -*- coding: utf-8 -
+
+class BadObjectDeclaration(Exception):
+
+    def __init__(self, value):
+        Exception.__init__(self)
+        self.value = value
+
+    def __str__(self):
+        return "BadObjectDeclaration: %s" % self.value
+

File internals.py

View file
+# -*- coding: utf-8 -
+
+import logging
+import inspect
+
+from rdf.rdfproperty import RdfProperty
+from rdf.rdfpropertyfactory import get_rdfproperty_by_value
+
+sacred_attr = ["__class__", "__dict__"]
+
+def get_all_rdf_properties(self):
+    props = {}
+    for attr, prop in self.__dict__.items():
+        if (type(self.__dict__[attr]) == self._filter_attrs):
+            props[attr] = prop
+    return props
+
+def get_attr(self, attr):
+    print "Attribute: %s" % attr
+    if (attr in sacred_attr):
+        return eval("self.%s" % attr)
+    elif (not attr in self.__dict__):
+        raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr))
+    elif(isinstance(self.__dict__[attr], RdfProperty)):
+        return getattr(self.__dict__[attr], "value")
+    else:
+        return self.__dict__[attr]
+
+def set_attr(self, attr, value):
+    print "Attribute: %s" % attr
+    if (type(self.__dict__[attr]) == RdfProperty):
+        self.__dict__[attr] = get_rdfproperty_by_value(self.__dict__[attr].curie, value)
+    elif isinstance(self.__dict__[attr], RdfProperty):
+        setattr(self.__dict__[attr], "value", value)
+    else:
+        self.__dict__[attr] = value
+
+def dump(obj):
+    #print vars(wikier)
+    name = "obj"
+    if ("__name__" in dir(obj)):
+        name = obj.__name__
+    for attr in obj.__dict__:
+#        if (attr in sacred_attr or attr.startswith("_")):
+#            pass
+#        else:
+#            value = getattr(obj, attr)
+#            if (inspect.ismethod(value)):
+#                pass
+#            else:
+#                print "%s.%s = %s" % (name, attr, value)
+        if (isinstance(obj.__dict__[attr], RdfProperty)):
+            print "%s.%s = %s" % (name, attr, object.__getattribute__(obj, attr))
+

File pryoo.yaml

View file
+
+pryoo:
+
+  persistence: 
+    #type: "memory"
+    type: "endpoint"
+    endpoint: "http://localhost:8890/sparql"
+    graph: "http://pryoo.wikier.org"
+    
+  general:
+    network:
+      proxy:
+        host: ""
+        port: ""
+        user: ""
+        pass: ""
+

File rdf/__init__.py

View file
+# -*- coding: utf-8 -
+
+from namespacesmanager import NamespacesManager
+from rdfresource import RdfResource
+from rdfproperty import RdfProperty
+from curie import CURIE
+

File rdf/curie.py

View file
+# -*- coding: utf-8 -
+
+from namespacesmanager import NamespacesManager
+
+class CURIE:
+
+    def __init__(self, curie):
+        if (curie.__class__ == CURIE):
+            self.prefix = curie.prefix
+            self.reference = curie.reference
+        else:
+            if (not curie or len(curie)==0):
+                raise ValueError("Empty CURIE is not valid")
+            splitted = curie.split(":")
+            if (len(splitted) != 2):
+                raise ValueError("Not valid CURIE syntax: %s" % curie)
+            else:
+                self.prefix = splitted[0]
+                self.reference = splitted[1]
+                if (self.prefix and self.reference):               
+                    ns = NamespacesManager().get_namespace(self.prefix)
+                    if (ns == None):
+                        raise ValueError("Namespace not registered for prefix '%s'" % self.prefix)
+
+                    #FIXME: validate formed URI
+                else:
+                    raise ValueError("Invalid query definition: %s" % self)
+
+    #FIXME make 'prefix' and 'reference' inmutable (set_value)
+
+    def __str__(self):
+        return "%s:%s" % (self.prefix, self.reference)
+
+    def __repr__(self):   
+        return str(self)
+
+    def __cmp__(self, o):
+        if (type(o) == str or type(o) == unicode):
+            return cmp(str(self), o)
+        else:
+            return cmp(str(self), str(o))
+
+    def __hash__(self):
+        return hash(str(self))
+

File rdf/namespacesmanager.py

View file
+# -*- coding: utf-8 -
+
+import logging
+from pryoo.utils.prefix import getNamespace, getPrefix
+from pryoo.utils.collections import dict2list, find_key
+
+class NamespacesManager:
+    """NamespaceManager using the Borg design pattern"""
+
+    __shared_state = { "ns" : {
+                                "xsd"  : "http://www.w3.org/2001/XMLSchema#",
+                                "rdf"  : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+                                "rdfs" : "http://www.w3.org/2000/01/rdf-schema#",
+                                "owl"  : "http://www.w3.org/2002/07/owl#",
+                                "dct"  : "http://purl.org/dc/terms/",
+                                "foaf" : "http://xmlns.com/foaf/0.1/",
+                                "sioc" : "http://rdfs.org/sioc/ns#",
+                                "con" : "http://www.w3.org/2000/10/swap/pim/contact#",
+                                "session" : "http://redfoot.net/2005/session#",
+                                "rel" : "http://purl.org/vocab/relationship/",
+                                "openid" : "http://xmlns.openid.net/auth#",
+                                "uranai" : "http://kota.s12.xrea.com/vocab/uranai#",
+                                "relation" : "http://vocab.org/relationship/",
+                             }
+                     }
+
+    def __init__(self):
+        if (not "ns" in self.__dict__):
+            self.__dict__ = self.__shared_state
+            self.__class__.__dict__["_NamespacesManager__shared_state"]["ns"] = self.ns #FIXME
+
+    def get_namespace(self, prefix):
+        if (prefix in self.ns):
+            return self.ns[prefix]
+        else:
+            logging.debug("Mapping for prefix '%s' not found, trying to retrieve it..." % prefix)
+            ns = getNamespace(prefix)
+            if (ns):
+                self.ns[prefix] = ns
+                return ns
+            else:
+                return None
+
+    def get_curie(self, uri):
+        char = "/"
+        if ("#" in uri): char = "#"
+        splitted = uri.strip().split(char)
+        ref = splitted[-1]
+        ns = uri[:-len(ref)]
+
+        prefix = None
+        if (ns in self.ns.values()):
+            prefix = find_key(self.ns, ns)
+        else:
+            logging.error("Prefix not found for namespace '%s', trying to retrieve it..." % ns)
+            prefix = getPrefix(ns)
+        if (prefix):
+            self.ns[prefix] = ns
+            #return CURIE("%s:%s" % (prefix,ref))
+            return "%s:%s" % (prefix,ref)
+        else:
+            return None
+
+    def get_namespaces_sparql(self):
+        return " \n".join(map(lambda i: "PREFIX %s: <%s>" % (i[0],i[1]), dict2list(self.ns)))
+

File rdf/rdfproperty.py

View file
+# -*- coding: utf-8 -
+
+import logging
+from curie import CURIE
+
+class RdfProperty(object):
+
+    value = None
+
+    def __init__(self, curie, value=None):
+        self.curie = CURIE(curie)
+        self.value = value
+
+    def __str__(self):
+        if (self.value):
+            return "%s(%s)=%s" % (self.__class__.__name__, self.curie, self.value)
+        else:
+            return "%s(%s)" % (self.__class__.__name__, self.curie)
+
+    def __repr__(self):
+        return str(self)
+
+class RdfPropertyLiteral(RdfProperty):
+
+    pass
+
+class RdfPropertyReference(RdfProperty):
+
+    data = None
+
+    def refresh(self):
+        logging.debug("Refreshing data of <%s>" % self.value)
+        from rdfresource import RdfResource
+        data = RdfResource.retrieve(self.value)
+        self.data = data
+        return data
+
+    def __getattribute__(self, attr):
+        if (attr == "data"):
+            data = object.__getattribute__(self, "data")
+            if (data == None):
+                data = self.refresh()
+            return data
+        else:
+            return object.__getattribute__(self, attr)
+
+class RdfPropertyMultivaluated(RdfProperty):
+
+    def __str__(self):
+        return "%s: \n\t%s" % (self.__class__.__name__, "\n\t".join([unicode(x) for x in self.value]))
+
+    def __len__(self):
+        return len(self.value)
+
+class RdfPropertyMultivaluatedLiteral(RdfPropertyMultivaluated):
+
+    def __getitem__(self, k):
+        if (self.value == None):
+            self.value = []
+        return self.value[k].value
+
+    def append(self, v):
+        if (self.value == None):
+            self.value = []
+        return self.value.append(v)
+
+class RdfPropertyMultivaluatedReference(RdfPropertyMultivaluated):
+
+    def __getitem__(self, k):
+        if (self.value == None):
+            self.value = {}
+        return self.value[k].data
+
+    def __setitem__(self, k, v):
+        if (self.value == None):
+            self.value = {}
+        if (v.curie == self.curie):
+            self.value[k] = v
+        else:
+            pass
+
+    def has_key(self, k):
+        return self.value.has_key(k)
+
+    def keys(self):
+        return self.value.keys()
+
+    def values(self):
+        return self.value.values()
+
+    def iteritems(self):
+        return self.value.iteritems()
+

File rdf/rdfpropertyfactory.py

View file
+# -*- coding: utf-8 -
+
+import logging
+from rdfproperty import RdfProperty, RdfPropertyLiteral, RdfPropertyReference
+
+def get_rdfproperty_from_sparql(curie, t, value):
+    if (t == "uri"):
+        if (value.startswith("http://")):
+            return RdfPropertyReference(curie, value)
+        else:
+            #logging.debug("ignoring blank nodes")
+            return None
+    elif (t == "literal"):
+        return RdfPropertyLiteral(curie, value)
+    else:
+        #logging.debug("ignoring unknown property type")
+        return None
+
+def get_rdfproperty_by_value(curie, value):
+    prop = None
+    if (value.startswith("http://")):
+        prop = RdfPropertyReference
+    else:
+        prop = RdfPropertyLiteral
+    return prop(curie, value)
+

File rdf/rdfresource.py

View file
+# -*- coding: utf-8 -
+
+import logging
+from rdfproperty import RdfProperty, RdfPropertyLiteral, RdfPropertyReference, RdfPropertyMultivaluated, RdfPropertyMultivaluatedLiteral, RdfPropertyMultivaluatedReference
+from rdfpropertyfactory import get_rdfproperty_from_sparql, get_rdfproperty_by_value
+from curie import CURIE
+from sparql import exec_query
+from types import MethodType
+from namespacesmanager import NamespacesManager
+from pryoo.session import Session
+from pryoo.internals import get_attr, set_attr, get_all_rdf_properties
+from pryoo.exceptions import BadObjectDeclaration
+from pryoo.utils.collections import clean_list
+
+class MetaRdfResource(type):
+    """
+    MetaClass for all RDF resources
+    """
+
+    def __new__(cls, name, bases, attrs):
+        super_new = super(MetaRdfResource, cls).__new__
+        parents = [b for b in bases if isinstance(b, MetaRdfResource)]
+        if not parents:
+            # If this isn't a subclass of Model, don't do anything special (trick from django models)
+            return super_new(cls, name, bases, attrs)
+
+        #attributes proxy
+        cls.__setattr__ = MethodType(set_attr, cls)
+        cls.__getattribute__ = MethodType(get_attr, cls) 
+        #there is an intentional asymmetry between __getattr__ and __setattr__
+        #see the __getattribute__ method for a way to actually get total control in new-style classes
+        #from http://pyref.infogami.com/__getattr__
+        #FIXME: http://www.megasolutions.net/python/Bypassing_setattr_for-changing-special-attributes-15936.aspx
+
+        module = attrs.pop("__module__")
+        new_class = super_new(cls, name, bases, {"__module__": module})
+
+        #FIXME: register resource
+        print new_class
+        return new_class
+
+class RdfResource(object):
+
+    #__metaclass__ = MetaRdfResource
+
+    def __init__(self, rdftype=[]):
+        self.uri = None
+        self.rdftype = self._preprocess_rdftype(rdftype)
+        self._filter_attrs = RdfProperty
+        #self.__dict__["__getattribute__"] = MethodType(get_attr, self, self.__class__)   
+        #self.__dict__["__setattr__"] = MethodType(set_attr, self, self.__class__)      
+
+    def _preprocess_rdftype(self, rdftype):
+        if (type(rdftype) == list or type(rdftype) == set):
+            types = [x.strip() for x in rdftype] 
+        elif (type(rdftype) == str):
+            types = [x.strip() for x in rdftype.split(",")]
+        else:
+            types = []
+        return [CURIE(x) for x in clean_list(types)]
+
+    def _add_triple(self, prop):
+        prefix = prop.curie.prefix
+        ref = prop.curie.reference
+        attr = "%s_%s" % (prefix, ref)
+        self.__dict__[attr] = prop
+
+    def _add_triples(self, triples={}):
+        for prop in triples.values():
+            self._add_triple(prop)
+
+    def __getattribute__(self, attr):
+        if (not attr.startswith("_") and object.__getattribute__(self, attr) and isinstance(object.__getattribute__(self, attr), RdfProperty)):
+            if (isinstance(object.__getattribute__(self, attr), RdfPropertyMultivaluated)):
+                return object.__getattribute__(self, attr)
+            else:
+                return getattr(self.__dict__[attr], "value")
+        else:
+            return object.__getattribute__(self, attr)
+
+    def __setattr__(self, attr, value):
+        if (attr in self.__dict__):
+            if (type(self.__dict__[attr]) == RdfProperty):
+                self.__dict__[attr] = get_rdfproperty_by_value(self.__dict__[attr].curie, value)
+            elif isinstance(self.__dict__[attr], RdfProperty):
+                setattr(self.__dict__[attr], "value", value)
+            else:
+                self.__dict__[attr] = value
+        else:
+            self.__dict__[attr] = value
+        
+    def __str__(self):
+        if hasattr(self, '__unicode__'):
+            return force_unicode(self).encode('utf-8')
+        return '%s object' % self.__class__.__name__
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__) and self._get_uri() == other._get_uri()
+
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
+    def get_uri(self):
+        return self.uri
+
+    def set_uri(self, uri):
+        self.uri = uri
+
+    def save(self):
+        session = Session()
+        props = get_all_rdf_properties(self)
+        query = "INSERT INTO GRAPH <%s> { \n" % session.getConfiguration("/persistence/graph")
+        for name, prop in props.items():
+            query += "%s %s '%s' . \n" % ("_:v", prop.curie, prop.value)
+        query += "} \n"
+        result = exec_query(session.getConfiguration("/persistence/endpoint"), query) 
+        print(result)
+
+    def delete(self):
+        print("delete(): TODO")
+
+    def refresh(self):
+        print("refresh(): TODO")
+
+    @classmethod
+    def find_all(cls):
+        if (cls == RdfResource):
+            raise NotImplementedError("this method requires a concrete RDF Resource definition")
+        else:
+            print("find_all(): TODO")
+
+    @classmethod
+    def retrieve(cls, uri):
+        if (cls != RdfResource):
+            raise NotImplementedError("todo")
+        else:
+            session = Session()
+            query = "SELECT ?p ?o FROM <%s> WHERE { <%s> ?p ?o }" % (session.getConfiguration("/persistence/graph"), uri)
+            results = exec_query(session.getConfiguration("/persistence/endpoint"), query) 
+            resource = RdfResource.build_resource(uri, results)
+            return resource
+
+    @classmethod
+    def build_resource(cls, uri, data={}):
+        nsman = NamespacesManager()
+        rdftypes = set()
+        triples = {}
+        for row in data["results"]["bindings"]:
+            p = row["p"]["value"]
+            o = row["o"]["value"]
+            curie = nsman.get_curie(p)
+            if (curie):
+                if (curie == "rdf:type"):
+                    rdftypes.add(nsman.get_curie(o))
+                else:
+                    triple = get_rdfproperty_from_sparql(curie, row["o"]["type"], o)
+                    if (triple):
+                        if (curie in triples):
+                            if (type(triple) == RdfPropertyLiteral):
+                                if (type(triples[curie]) == RdfPropertyLiteral):
+                                    tmp = triples[curie] 
+                                    triples[curie] = RdfPropertyMultivaluatedLiteral(curie)
+                                    triples[curie].append(tmp)
+                                    triples[curie].append(triple)
+                                elif (type(triples[curie]) == RdfPropertyMultivaluatedLiteral):
+                                    triples[curie].append(triple)
+                                else:
+                                    pass
+                            elif (type(triple) == RdfPropertyReference):
+                                if (type(triples[curie]) == RdfPropertyReference):
+                                    tmp = triples[curie] 
+                                    triples[curie] = RdfPropertyMultivaluatedReference(curie)
+                                    triples[curie][tmp.value] = tmp
+                                    triples[curie][triple.value] = triple
+                                elif (type(triples[curie]) == RdfPropertyMultivaluatedReference):
+                                    triples[curie][triple.value] = triple
+                                else:
+                                    pass
+                            else:
+                                pass
+                        else:
+                            triples[curie] = triple
+                    else:
+                        pass
+            else:
+                logging.error("No proper CURIE can be build for '%s', so ignoring this triple..." % p)
+
+        #FIXME: actually we should create a class with one of the rdftypes...
+        resource = cls(rdftypes)
+        resource.set_uri(uri)
+        resource._add_triples(triples)
+        return resource
+
+
+    def __str__(self):
+        if (self.uri):
+            return "RdfResource(%s,%s)" % (self.uri, self.rdftype)
+        else:
+            return "RdfResource(%s)" % self.rdftpe
+
+    def __repr__(self):
+        return str(self)
+

File rdf/sparql/__init__.py

View file
+# -*- coding: utf-8 -
+
+from query import exec_query
+

File rdf/sparql/query.py

View file
+# -*- coding: utf-8 -
+
+import logging
+from SPARQLWrapper import SPARQLWrapper, JSON
+from pryoo.rdf import NamespacesManager
+import urllib2
+
+def exec_query(endpoint, query):
+    ns = NamespacesManager()
+    prefixes = ns.get_namespaces_sparql()
+    sparql = SPARQLWrapper(endpoint)
+    sparql.setQuery("%s \n%s" % (prefixes, query))
+    sparql.setReturnFormat(JSON)
+    logging.debug("Performing query:\n\t%s\n" % sparql.queryString.replace("\n", "\n\t"))
+    try:
+        return sparql.query().convert()
+    except urllib2.URLError, e:
+        logging.error("Error performing query: %s" % e.reason)
+        return { "results" : { "bindings" : [] } }
+

File session.py

View file
+# -*- coding: utf-8 -
+
+import os
+import logging
+import yaml
+
+class Session:
+    """Session using the Borg design pattern"""
+
+    __shared_state = { "conf" : {"path" : None, "data" : None} }
+
+    def __init__(self, path=None):
+        self.__dict__ = self.__shared_state
+
+        if (self.conf["data"] == None):
+            if (path == None):
+                logging.info("No configuration found, so using a default one... (memory store and so on)")
+                self.conf["data"] = { "persistence" : { "type" : "memory" } } 
+            else:
+                self.conf["path"] = os.path.abspath(path)
+                logging.debug("Reading pryoo's configuration from '%s'..." % self.conf["path"])
+                if (not os.path.exists(self.conf["path"])):
+                    logging.error("Error reading from '%s': file does not exist" % self.conf["path"])
+                    parts = __file__.split("/")
+                    base = "/".join(parts[:-1])
+                    self.conf["path"] = "%s/%s" % (base, path)
+                    logging.debug("Reading pryoo's configuration from '%s'..." % self.conf["path"])
+                    if (not os.path.exists(self.conf["path"])):
+                        raise ValueError("Not found a proper file at '%s' with a configuration for pryoo. Please, provide a right path" % self.path)
+                try:
+                    self.conf["data"] = yaml.load(open(self.conf["path"], "r"))["pryoo"]
+                except Exception as e:
+                    raise ValueError(e, "Error loading pryoo's configuration: %s" % e)
+
+            self.__class__.__dict__["_Session__shared_state"]["conf"]["data"] = self.conf["data"] #FIXME
+
+    def getConfiguration(self, path):
+        """
+        Get the value of an option using XPath expressions
+        @param path: path to access the option
+        @type path: str
+        @return: value of that option, None if it doesn't exist
+        @rtype: object
+        """
+        exp = self._constructExp(path)
+        try:
+            return eval(exp)
+        except KeyError:
+            return None
+
+    def _constructExp(self, path):
+        base= "self.conf['data']"
+        path = path.split("/")[1:]
+        if (len(path)==0):
+            return "None"
+        else:
+            if (len(path[0])==0):
+                return base
+            else:
+                return "%s['%s']" % (base, "']['".join(path))
+

File utils/__init__.py

View file
+# -*- coding: utf-8 -
+

File utils/collections.py

View file
+# -*- coding: utf-8 -
+
+def clean_list(l, bads=[None, ""]):
+    for bad in bads:
+        l = remove_values_from_list(l, bad)
+    return l
+
+def remove_values_from_list(l, v):
+    while v in l:
+        l.remove(v)
+    return l
+
+dict2list = lambda d: [(k, v) for (k, v) in d.iteritems()]
+
+def find_key(d, val):
+    key = [k for k, v in d.iteritems() if v == val]
+    if (len(key) == 0):
+        return None
+    elif (len(key) == 1):
+        return key[0]
+    else:
+        return key
+
+def intersection(d1, d2):
+    return [item for item in d1.keys() if d2.has_key(item)]
+

File utils/namespacesmanager.py

View file
+# -*- coding: utf-8 -
+
+#FIXME: singleton
+class NamespacesManager:
+
+
+    

File utils/prefix.py

View file
+# -*- coding: utf-8 -
+
+import logging
+import urllib
+import urllib2
+
+def getNamespace(prefix, service="http://prefix.cc"):
+    if (service.endswith("/")): service = service[:-1]
+    url = "%s/%s.file.txt" % (service, prefix)
+    opener = urllib2.build_opener()
+    opener.addheaders = [("User-agent", "pryoo (http://pryoo.googlecode.com)")]
+    try:
+        f = opener.open(url)
+    except urllib2.HTTPError, e:
+        logging.error("Error retrieving prefix '%s' from '%s': %s" % (prefix, service, e))
+        return None
+    
+    data = f.read()
+    line = data.split("\n")[0]
+    mapping = line.split("\t")
+    if (mapping[0] == prefix):
+        logging.debug("Successfully retreived namespace mapping for prefix '%s' (%s) from '%s'" % (prefix, mapping[1], service))
+        return mapping[1]
+    else:
+        logging.error("Both prefixes ('%s' and '%s') don't match" % (prefix, mapping[0]))
+        return None
+
+def getPrefix(namespace, service="http://prefix.cc"):
+    params = urllib.urlencode({"uri": namespace, "format": "txt"})
+    url = "%s/reverse?%s" % (service, params)
+    opener = urllib2.build_opener()
+    opener.addheaders = [("User-agent", "pryoo (http://pryoo.googlecode.com)")]
+    try:
+        f = opener.open(url)
+    except urllib2.HTTPError, e:
+        logging.error("Error retrieving prefix for namespace '%s' from '%s': %s" % (namespace    , service, e))
+        return None
+    
+    data = f.read()
+    line = data.split("\n")[0]
+    mapping = line.split("\t")
+    if (mapping[1] == namespace):
+        logging.debug("Successfully retreived prefix mapping for namespace '%s' (%s) from '%s'" % (namespace, mapping[0], service))
+        return mapping[0]
+    else:
+        logging.error("Both namespaces ('%s' and '%s') don't match" % (namespace, mapping[1]))
+        return None
+

File utils/trace.py

View file
+# -*- coding: utf-8 -
+
+def traced(f):
+    def tracer(*args, **kw):
+        print(("** %s(%s)") % (
+                f.__name__,
+                ", ".join(
+                     [repr(arg) for arg in args]+
+                     ["%s=%s" % (k, repr(v))
+                         for (k, v) in kw.items()])))
+        return f(*args, **kw)
+    return tracer
+