from __future__ import generators import os from urlparse import urlparse from rdflib.syntax.parser import Parser from rdflib.syntax.nt_parser import NTParser from rdflib.syntax.serializer import Serializer from rdflib import URIRef from rdflib.URLInputSource import URLInputSource from threading import Lock from xml.sax.xmlreader import InputSource from urlparse import urljoin from os import getcwd class LoadSave(NTParser, Parser, Serializer, object): """LoadSave Mixed-in with a store that implements add and visit and provides I/O for that class. Also, needs to be mixed in with something that provides parse_URI and output methods. """ def __init__(self): super(LoadSave, self).__init__() self.location = None self.__lock = Lock() def load(self, location): if isinstance(location, InputSource): self.parse(location) else: location = urljoin("file://%s/" % getcwd(), location) scheme, netloc, path, params, query, fragment = urlparse(location) if netloc=="": # If local and it does not exist then create one. if not os.access(path, os.F_OK): # TODO: is this equiv to os.path.exists? self.save(path) if location[-3:]==".nt": self.parse_nt_URI(location, None) else: source = URLInputSource(location) self.parse(source) if not self.location: self.location = location def save(self, location=None): try: self.__lock.acquire() location = location or self.location if not location: print "WARNING: not saving as no location has been set" return scheme, netloc, path, params, query, fragment = urlparse(location) if netloc!="": print "WARNING: not saving as location is not a local file reference" return import tempfile, shutil, os name = tempfile.mktemp() stream = open(name, 'wb') self.output(stream) stream.close() if os.path.isfile(path): os.remove(path) shutil.copy(name, path) os.unlink(name) finally: self.__lock.release()