While trying to test a Django command by passing a file object as an argument:
a_file = open('Sample.xml', 'rb')
call_command("process_xml", a_file, self.valdate)
and parse the xml file in the command:
from lxml import etree, objectify
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
'a_file',
)
def __init__(self, **kwargs):
super(BaseCommand, self).__init__(**kwargs)
def handle(self, *args, **options):
xml_file = options["a_file"]
print(str(xml_file))
result = objectify.parse(xml_file)
I got the error:
File "/mnt/ccl/management/commands/process_xml.py", line 20, in handle
result = objectify.parse(xml_file)
File "src/lxml/objectify.pyx", line 1842, in lxml.objectify.parse
File "src/lxml/etree.pyx", line 3521, in lxml.etree.parse
File "src/lxml/parser.pxi", line 1859, in lxml.etree._parseDocument
File "src/lxml/parser.pxi", line 1885, in lxml.etree._parseDocumentFromURL
File "src/lxml/parser.pxi", line 1789, in lxml.etree._parseDocFromFile
File "src/lxml/parser.pxi", line 1177, in lxml.etree._BaseParser._parseDocFromFile
File "src/lxml/parser.pxi", line 615, in lxml.etree._ParserContext._handleParseResultDoc
File "src/lxml/parser.pxi", line 725, in lxml.etree._handleParseResult
File "src/lxml/parser.pxi", line 652, in lxml.etree._raiseParseError
OSError: Error reading file '<_io.BufferedReader name='/mnt/ccl/Sample.xml'>': failed to load external entity "<_io.BufferedReader name='/mnt/ccl/Sample.xml'>"
However, if I open the file within the command module,
with open('/mnt/ccl/Sample.xml', 'rb') as xml_file:
result = objectify.parse(xml_file)
There was no issue.
It looked as if the str() function was applied on the fileobject before it was passed to the command and hence it was a string when it was referenced.
Really appreciate if someone could point to a solution.
question from:
https://stackoverflow.com/questions/65909518/issue-with-passing-a-file-object-as-an-argument-of-django-command