Search code examples
pythonamazon-web-serviceslxmltastypie

Tastypie : Usage of the XML aspects requires lxml and defusedxml


I'm getting the following error while running Tastypie from production server whilst it's working fine in development environment :

File "/opt/python/run/venv/lib/python2.7/site-packages/tastypie/serializers.py" in to_xml
446. "Usage of the XML aspects requires lxml and defusedxml.")

Usage of the XML aspects requires lxml and defusedxml.

When I check for the packages, I can find them :

(venv)[root@prod app]# pip freeze |grep xml
defusedxml==0.4.1
lxml==3.6.0

When I check the import from the file site-packages/tastypie/serializers.py and reproduce it in a Python console in the production environment it works :

(venv)[root@prod app]# python
Python 2.7.10 (default, Dec  8 2015, 18:25:23) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
...     import defusedxml.lxml as lxml
...     from defusedxml.common import DefusedXmlException
...     from defusedxml.lxml import parse as parse_xml
...     from lxml.etree import Element, tostring, LxmlError
... except ImportError:
...     lxml = None
... 
>>> lxml is None
False

The to_xml fails on the lxml is None test :

def to_xml(self, data, options=None):
    """
    Given some Python data, produces XML output.
    """
    options = options or {}

    if lxml is None:
        raise ImproperlyConfigured(
            "Usage of the XML aspects requires lxml and defusedxml.")

    return tostring(self.to_etree(data, options), xml_declaration=True,
        encoding='utf-8')

And the direct call to the to_xml method works :

(venv)[root@prod app]# python
Python 2.7.10 (default, Dec  8 2015, 18:25:23) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from tastypie.serializers import Serializer
>>> Serializer().to_xml({"test":"test"})
"<?xml version='1.0' encoding='utf-8'?>\n<response><test>test</test></response>"
>>> 

I tried uninstalling/reinstalling lxml and defusedxml, I tried restarting the production, any more ideas would be most welcome.

Server is on AWS Beanstalk RHEL (Amazon Linux) environment / Python 2.7.


Solution

  • If you ever have this problem, the reason is that indeed, the path where is installed the library is not in your Apache Python path.

    The problem from my side was that I installed the package manually and it went in the dist-package directory instead of the site-package directory where all the other packages automaticaly installed were.