Skip to content
Advertisement

Why BINARY usage in SQLAlchemy with Python3 cause a TypeError: ‘string argument without an encoding’

I read a lot of similar questions but none of the clearly answer my issue.

I’m using sqlalchemy-utils EncryptedType on a mysql table column.
The table creation and the insert is ok, but when I’m trying to do a query a receive:

JavaScript

I found out that this error occurs only using python 3, not using python 2.
And also that the problem is with the sqlalchemy bynary type, because I get the same error with Binary, Varbinary, and Blob columns.
Since bytes in python3 needs an encoding for strings, I changed the code of sqlalchemysqlsqltypes.py on line 944 to value = bytes(value, 'utf-8) and al works well, so my question is:

why I need to change the sqlalchemy code? Is sqlalchemy fully usable with python3? Is it safe to change the code of a package?

Here is a code sample to try:

JavaScript

Advertisement

Answer

Thanks to the hint provided by Ilja Everilä, I was able to find a solution. Maybe not the best solution, but now is working.

I think that the root cause is that my DB-API automatically converts bytes to str during the query. So I just disabled this behavior by adding a parameter to the create_engine:

engine = create_engine("mysql+mysqlconnector://%(user)s:%(password)s@%(host)s/%(database)s" % DB_CONFIG, connect_args={'use_unicode': False})

The consequence is that if you have a String column it will be returned in queries as bytes not as ‘str’, and you have to manually decode it.

Surely there is a better solution.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement