Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autodetect parse() format #1046

Merged
merged 8 commits into from
Jun 1, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
from __future__ import division
from __future__ import print_function

from xml.sax import SAXParseException

from rdflib.term import Literal # required for doctests

assert Literal # avoid warning
from rdflib.namespace import Namespace # required for doctests

assert Namespace # avoid warning
import rdflib.util # avoid circular dependency


__doc__ = """\
Expand Down Expand Up @@ -1070,13 +1073,24 @@ def parse(
)
if format is None:
format = source.content_type
assumed_xml = False
if format is None:
# raise Exception("Could not determine format for %r. You can" + \
# "expicitly specify one with the format argument." % source)
format = "application/rdf+xml"
try:
format = rdflib.util.guess_format(source.file.name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Under what circumstances are you seeing these errors? I'm guessing when source.file.name is None for the TypeError and probably ... when not hasattr(source, 'file')? If that is the case then an explicit test (if statement) for the presence and non-Noneness of the values would be much clearer here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tgbugs I've adopted your suggestion for more of a look-before-you-leap approach with an explicit if-statement guard, ensuring that source.file.name is an accessible path and is a string before attempting a call to guess_format.

except (AttributeError, TypeError):
pass
if format is None:
format = "application/rdf+xml"
assumed_xml = True
parser = plugin.get(format, Parser)()
try:
parser.parse(source, self, **args)
except SAXParseException as saxpe:
if assumed_xml:
logger.warning(
"Could not guess format for %r, so assumed xml."
" You can explicitly specify format using the format argument." % source)
raise saxpe
finally:
if source.auto_close:
source.close()
Expand Down
11 changes: 5 additions & 6 deletions rdflib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@
from rdflib.exceptions import ObjectTypeError
from rdflib.exceptions import PredicateTypeError
from rdflib.exceptions import SubjectTypeError
from rdflib.graph import Graph
from rdflib.graph import QuotedGraph
import rdflib.graph # avoid circular dependency
from rdflib.namespace import Namespace
from rdflib.namespace import NamespaceManager
from rdflib.term import BNode
Expand Down Expand Up @@ -146,7 +145,7 @@ def from_n3(s, default=None, backend=None, nsm=None):
>>> from rdflib import RDFS
>>> from_n3('rdfs:label') == RDFS['label']
True
>>> nsm = NamespaceManager(Graph())
>>> nsm = NamespaceManager(rdflib.graph.Graph())
>>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/')
>>> berlin = URIRef('http://dbpedia.org/resource/Berlin')
>>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin
Expand Down Expand Up @@ -192,16 +191,16 @@ def from_n3(s, default=None, backend=None, nsm=None):
return Literal(int(s))
elif s.startswith('{'):
identifier = from_n3(s[1:-1])
return QuotedGraph(backend, identifier)
return rdflib.graph.QuotedGraph(backend, identifier)
elif s.startswith('['):
identifier = from_n3(s[1:-1])
return Graph(backend, identifier)
return rdflib.graph.Graph(backend, identifier)
elif s.startswith("_:"):
return BNode(s[2:])
elif ':' in s:
if nsm is None:
# instantiate default NamespaceManager and rely on its defaults
nsm = NamespaceManager(Graph())
nsm = NamespaceManager(rdflib.graph.Graph())
prefix, last_part = s.split(':', 1)
ns = dict(nsm.namespaces())[prefix]
return Namespace(ns)[last_part]
Expand Down
32 changes: 32 additions & 0 deletions test/test_parse_file_guess_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import unittest
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory

from xml.sax import SAXParseException

from rdflib import Graph, logger as graph_logger


class FileParserGuessFormatTest(unittest.TestCase):
def test_ttl(self):
g = Graph()
self.assertIsInstance(g.parse("test/w3c/turtle/IRI_subject.ttl"), Graph)

def test_n3(self):
g = Graph()
self.assertIsInstance(g.parse("test/n3/example-lots_of_graphs.n3"), Graph)

def test_warning(self):
g = Graph()
with TemporaryDirectory() as tmpdirname:
newpath = Path(tmpdirname).joinpath("no_file_ext")
copyfile("test/w3c/turtle/IRI_subject.ttl", str(newpath))
with self.assertLogs(graph_logger, "WARNING") as log_cm:
with self.assertRaises(SAXParseException):
g.parse(str(newpath))
self.assertTrue(any("Could not guess format" in msg for msg in log_cm.output))


if __name__ == '__main__':
unittest.main()