Search code examples
pythonsparql

Python with sparql-client - ImportError: cannot import name 'encodestring' from 'base64'


I am Python newbie. Trying to use this module https://pypi.org/project/sparql-client/

module.py

from sparql import Service


class MyModule:

    def my_method(self):
        s = Service('https://my-endpoint:8182/sparql', "utf-8", "GET")
        statement = """
            MOVE uri:temp_graph TO uri:user_graph
            ADD uri:temp_graph TO uri:user_graph    
        """.format(user_graph="http://aws.amazon.com/account-uid",
                   temp_graph="http://aws.amazon.com/account-uid-temp")
        s.query(statement)

I am trying to test it

test_module.py

import unittest

from unittest.mock import patch, Mock

class TestModule(unittest.TestCase):

    @patch('sparql.Service', autospec=True)
    def test_mymethod(self, sparql_mock):
        sparql_instance = sparql_mock.return_value
        sparql_instance.query = Mock()

While running I get

  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 1564, in <lambda>
    getter = lambda: _importer(target)
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 1236, in _importer
    thing = __import__(import_path)
  File "/usr/local/lib/python3.9/site-packages/sparql.py", line 50, in <module>
    from base64 import encodestring
ImportError: cannot import name 'encodestring' from 'base64' (/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/base64.py)

So it can not import this line

https://github.com/eea/sparql-client/blob/master/sparql.py#L50

Any idea how to fix this?


Solution

  • The problem is caused by the version of base64 module you are running while the version of sparql you have installed is dependent on a lower version of the base64 module. The sparql is dependent on base64 version built for python3.1. encodestring() and decodestring() have since been deprecated.

    • Option 1 - Your best bet (if you must continue using this version of sparql) is to downgrade your version of python to 3.1 from 3.9 which is your current version.
    • Option 2 - will be to adopt the new specifications for the current version of base64 you have installed. this will mean updating sparql and anywhere you are calling deprecated methods of base64.

    If you choose to go with option 2, then open the sparql module and edit the import statement. Change from base64 import encodestring to from base64 import encodebytes and replace any occurrences of encodestring with encodebytes in your code and any module you have dependent on base64. That should solve your problem.