Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python 3.x - Issue with passing a file object as an argument of Django command

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...