This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.
(source, base="")
| 336 | # --- Utility functions |
| 337 | |
| 338 | def prepare_input_source(source, base=""): |
| 339 | """This function takes an InputSource and an optional base URL and |
| 340 | returns a fully resolved InputSource object ready for reading.""" |
| 341 | |
| 342 | if isinstance(source, os.PathLike): |
| 343 | source = os.fspath(source) |
| 344 | if isinstance(source, str): |
| 345 | source = xmlreader.InputSource(source) |
| 346 | elif hasattr(source, "read"): |
| 347 | f = source |
| 348 | source = xmlreader.InputSource() |
| 349 | if isinstance(f.read(0), str): |
| 350 | source.setCharacterStream(f) |
| 351 | else: |
| 352 | source.setByteStream(f) |
| 353 | if hasattr(f, "name") and isinstance(f.name, str): |
| 354 | source.setSystemId(f.name) |
| 355 | |
| 356 | if source.getCharacterStream() is None and source.getByteStream() is None: |
| 357 | sysid = source.getSystemId() |
| 358 | basehead = os.path.dirname(os.path.normpath(base)) |
| 359 | sysidfilename = os.path.join(basehead, sysid) |
| 360 | if os.path.isfile(sysidfilename): |
| 361 | source.setSystemId(sysidfilename) |
| 362 | f = open(sysidfilename, "rb") |
| 363 | else: |
| 364 | source.setSystemId(urllib.parse.urljoin(base, sysid)) |
| 365 | f = urllib.request.urlopen(source.getSystemId()) |
| 366 | |
| 367 | source.setByteStream(f) |
| 368 | |
| 369 | return source |
searching dependent graphs…