Search code examples
pythonoracle-databaseblob

Python: TypeError: a bytes-like object is required, not 'tuple'


i have some code below, which queries a database and extracts a BLOB. I would like to save this BLOB data as a file, however i am unable to do so. i have done some research and tried the various sample bits of code around but nothing seems to work.

import cx_Oracle
import db_config

con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)
cur = con.cursor()

def writeTofile(data, filename):
    print(data)
    print(filename)
    with open(filename, "wb") as file:
        file.write(data)
    print("Stored blob data into: ", filename, "\n")

def output_type_handler(cursor, name, default_type, size, precision, scale):
    if default_type == cx_Oracle.DB_TYPE_CLOB:
        return cursor.var(cx_Oracle.DB_TYPE_LONG, arraysize=cursor.arraysize)
    if default_type == cx_Oracle.DB_TYPE_BLOB:
        return cursor.var(cx_Oracle.DB_TYPE_LONG_RAW, arraysize=cursor.arraysize)

con.outputtypehandler = output_type_handler

   print("Querying data...")
cur.execute("select payload from table where id=101")
(blob_data) = cur.fetchone()
print("BLOB length:", len(blob_data))
print("BLOB data:", blob_data)
payload = blob_data
trigger = "C:\\Temp\\Training\\Python\\trigger.bin"
print(trigger)
writeTofile(payload, trigger) 

The response i get is below:

Enter password for DataBase:
Querying data...
BLOB length: 1
BLOB data: (b'5468616e6b7320666f722074616b696e67207468652074696d6520746f2068656c702c20697473206d756368206170726963617465642e',)
C:\Temp\Training\Python\trigger.bin
(b'5468616e6b7320666f722074616b696e67207468652074696d6520746f2068656c702c20697473206d756368206170726963617465642e',)
C:\Temp\Training\Python\trigger.bin
Traceback (most recent call last):
  File "C:\Temp\Training\Python\python-cx_Oracle-main\samples\tutorial\read_blob3.py", line 39, in <module>
    writeTofile(payload, trigger)
  File "C:\Temp\Training\Python\python-cx_Oracle-main\samples\tutorial\read_blob3.py", line 20, in writeTofile
    file.write(data)
TypeError: a bytes-like object is required, not 'tuple' 

I dont really understand why the writeTofile(payload, trigger) is mentioned as my print statement in the wrtietofile function shows the data is passed, what am i missing?

I thought i had to turn the data into a bytes array, but that then gave me a different error;

TypeError: 'bytes' object cannot be interpreted as an integer

Any help is much appriciated.


Solution

  • Type of payload is tuple, you need to call function as,

    writeTofile(payload[0], trigger)