Python Forum

Full Version: Flask Can't Save Screenshot to Postgres Db
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello to All,
Would you help resolve the following problem. The Flask web app I'm working on takes a screenshot (say of my computer - and it does work) and then insert/save that screenshot to Postgres db, which then the web app retrieves for displaying on the Jinja2 template. The seems to run with no errors but no saving to the db takes place. Thank for the help. This is my code:
from application import app
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
import pyscreenshot
import random
import string

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password_here@localhost:5432/database'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy()
db.init_app(app)

class Image(db.Model):
  __tablename__ = "images"
  id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  image = db.Column(db.String, nullable=True)
  def __repr__(self):
      return '<id={},image={}>'.format(self.id, self.image)
#======================================================================
def get_images(params=None):
    if not params:
        return Image.query.all()
#======================================================================
db.create_all()
@app.route('/')
@app.route('/homepage')
def homepage():
    return render_template('homepage.html')

@app.route('/get_screenshot', methods=['POST'])
def get_screenshot():
    im = pyscreenshot.grab()
    im.save('Screenshot3'):
    photo = Image(im)
    db.session.add(photo)
    db.session.commit()
    return render_template('homepage.html')

@app.route('/images/db/', methods=['GET'])
def get_images_from_db():
    images = get_images()#function to help retrieve images from db
    return render_template('show_images.html', images=images, target='db')
Hello guys, I'm still facing the same problem - unable to insert screenshot to Postgres db. I am attempting using another approach by using the SQL commands. The application is running without errors except that now the screen capture is done and still no insert to the db. Would help me to figure out what's wrong. Thank you for your help.
New code:
@app.route('/', methods=['GET'])
def get_screenshot():
    img = pyscreenshot.grab()
    img.save('Screenshot3')
    try:
        connection = psycopg2.connect(user="postgres",
                                  password="password_db",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="database")
        cursor = connection.cursor()
        postgres_insert_query = "INSERT INTO images (image) VALUES ('img')"
        cursor.execute(postgres_insert_query)
        connection.commit()
        flash ("Record inserted successfully into images table")
    except (Exception, psycopg2.Error) as error :
        if(connection):
            flash ("Failed to insert record into mobile table", error)
    finally:
        #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            flash ("PostgreSQL connection is closed")
have you seen this: https://kb.objectrocket.com/postgresql/u...tgres-1110
at quick glance, seems to solve your problem
I have seen other code, where the model data type for the image column is specified as 'bytea'
(Sep-21-2020, 08:42 PM)Larz60+ Wrote: [ -> ]have you seen this: https://kb.objectrocket.com/postgresql/u...tgres-1110
at quick glance, seems to solve your problem
I have seen other code, where the model data type for the image column is specified as 'bytea'

Thank you so much for your reply. I actually looked at it. The thing is that it deals with first uploading a file/image via a form request and then store it in "FileImage" which is then saved to the db. What I am doing is that I take a screenshot of my screen as in
    img = pyscreenshot.grab()
and once it's saved in
img.save()
then I need saved/insert it to the database. That's where I have problem with. Again thank you for the help.