0

I'm writing a tg bot. I need to save user's photo to the database. I use this code:

def parse_photo(file_path: str):
    with urllib.request.urlopen(f"https://api.telegram.org/file/bot{os.getenv('TOKEN')}/{file_path}") as f:
        html = f.read()
    return psycopg2.Binary(html)

and then I try to save to the DB binary object which is returned above. But I got this error:

psycopg2.errors.SyntaxError: syntax error at or near "<"
LINE 1: ...photo) VALUES (297850814, 'sdf', '09.04.2023', 7, <psycopg2....

So how to save a pic to the DB properly?

function which saves data to the DB:

def insert(table: str, column_values: Dict) -> None:
    columns = ', '.join(column_values.keys())
    values = tuple(column_values.values())
    q = f'''INSERT INTO {table} ({columns}) VALUES {values}'''
    cursor.execute(q)
    connection.commit()

update: I tried this code:

file_info = await bot.get_file(message.photo[len(message.photo) - 1].file_id)
data["photo"] = (await bot.download_file(file_info.file_path)).read()

and got this error:

psycopg2.errors.SyntaxError: syntax error at or near "("
LINE 1: ...c*@\x03\t+\xa0^U\x16n\x83)%\x005:F\xc9!H\x85\x1e\'(.\x1a\x90...

How to solve it?

pizhlo
  • 107
  • 6
  • What made you think this would work in the first place? Are you following some documentation or tutorial? – jjanes Apr 09 '23 at 14:50
  • @jjanes yes, I followed this article first: https://www.geeksforgeeks.org/save-a-image-file-on-a-postgres-database-python/ and then I found this question and followed it: https://stackoverflow.com/questions/67733841/how-to-save-photo-from-telegram-bot-aiogram-to-postgresql-database/67734071#67734071 – pizhlo Apr 09 '23 at 15:00
  • geeksforgeeks is a crapshow of popups, but it looks like you are supposed to pass the object to execute(), not interpolate it into a string using python's interpolation. (which you shouldn't do anyway, just for security reasons). – jjanes Apr 09 '23 at 17:28

0 Answers0