3

Hi I have a problem with type after I get blob from my query, here is the code

conn = MySQLdb.connect("mysqlblah", "user", "pass", "db")

cursor = conn.cursor()

data = []
queryString = "SELECT * FROM contentindex where tag LIKE '" + contentType + "%'"
cursor.execute(queryString)

rows = cursor.fetchall()
columns = [t[0] for t in cursor.description]
for row in rows:
    jsonRow = {}
    i = 0
    for column in columns:
        if column == "created":
            jsonRow[column] = str(row[i])
        elif column == "icon":
            icon = row[i]
            print icon
            jsonRow[column] = "data:image/(jpg);base64," + base64.b64encode(icon.getvalue())
        else:
            jsonRow[column] = row[i]
        i = i + 1
    data.append(jsonRow)

This prints <_io.BytesIO object at 0x01667810> and then throws 'str' object has no attribute 'getvalue' exception.

I'm pounding for days on this problem, any help will be greatly appreciated

5
  • This seems very strange. What happens if instead of print icon you try print icon.getvalue()? Commented Aug 13, 2015 at 11:53
  • I get this crash 'str' object has no attribute 'getvalue' Commented Aug 13, 2015 at 11:55
  • The BytesIO stuff seems like a red herring. It appears you are dealing with a str object. Assuming icon is the binary string you want it to be, does base64.b64encode(icon) accomplish what you need? Commented Aug 13, 2015 at 12:02
  • Looks like it gives me base64 string. I guess this is what i want.. Commented Aug 13, 2015 at 12:07
  • Is there any chance you have bad data in the database? Perhaps you accidentally saved the string representation of a BytesIO object to the database? (i.e. the BLOB literally holds the characters "<_io.BytesIO object at 0x01667810>") Commented Aug 13, 2015 at 12:16

1 Answer 1

3

It looks like MySQL converts the BLOB field type to a Python str.

Based on our conversation in the comments, I believe you have inadvertently stored a string with the value "<_io.BytesIO object at 0x01667810>" in this column rather than the actual data you wished to store. You can test whether this is the case in a couple of different ways:

print icon[0]  # I'm betting it will be '<'
print type(icon)  # Likely 'str'

In summary, it appears you have a data corruption issue as opposed to some sort of exotic issue with types.

Sign up to request clarification or add additional context in comments.

1 Comment

I checked your theory and you are absolutely correct. I found my wrong code where I was saving and did not do getvalue on my BytesIO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.