How to save a image file on a Postgres database?

前端 未结 5 1180
后悔当初
后悔当初 2021-01-31 06:21

For learning purposes, I\'m creating a site using Python+Flask. I want to recover an image from database and show it on screen. But one step at a time.

I have no idea ho

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-31 06:32

    import psycopg2
    import sys
    
    def readImage():
        try:
            fin = open("woman.jpg", "rb")
            img = fin.read()
            return img
    
        except IOError, e:
            print "Error %d: %s" % (e.args[0],e.args[1])
            sys.exit(1)
    
        finally:
            if fin:
                fin.close()
    try:
        con = psycopg2.connect(database="testdb", user="abc")
        cur = con.cursor()
        data = readImage()
        binary = psycopg2.Binary(data)
        cur.execute("INSERT INTO images(id, data) VALUES (1, %s)", (binary,) )
        con.commit()
    except psycopg2.DatabaseError, e:
        if con:
            con.rollback()
        print 'Error %s' % e    
        sys.exit(1)
    finally: 
        if con:
            con.close()
    

提交回复
热议问题