Zaid E.
Zaid E.

Reputation: 41

SQLAlchemy add_all() inserting not working

I have my Flask API endpoint that doesn't to be saving all the information from for loop The endpoint uploads multiple images. All is working fine, i.e the images are being uploaded however when it comes to inserting the names to the database, no record(file name/url) is being inserted.

Endpoint:

def upload_images(args):
    """Upload room images """
    image_id = None

    for file in request.files.getlist('image_name'):
        if file and allowed_file(file.filename):
            image_id = str(uuid.uuid4())
            filename = image_id + '.png'
            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

            #Resize Images
            _image_resize(current_app.config['UPLOAD_FOLDER'], image_id, 600, 'lg')
            _image_resize(current_app.config['UPLOAD_FOLDER'], image_id, 150, 'sm')
    get_image = RoomImages(**args)
    get_image.image_name = url_for('uploaded_file', filename=filename, _external=True)
    db.session.add_all(get_image)
    db.session.flush()
    db.session.commit()
    return get_image

Model:

class RoomImages(db.Model):
    __tablename__='ep_roomimages'

    id = sqla.Column(sqla.Integer, primary_key=True)
    image_name = sqla.Column(sqla.String(128), unique=True)
    room_id = sqla.Column(sqla.Integer, sqla.ForeignKey(Room.id), index=True)

    room_img = sqla_orm.relationship('Room', back_populates='room_images')


    def __repr__(self):
        return '<Room Images {}>'. format(self.image_name)

Error I am getting is: TypeError: 'RoomImages' object is not iterable

Upvotes: 0

Views: 575

Answers (1)

Zaid E.
Zaid E.

Reputation: 41

For those looking at this for a solution, here is my final edit. The code needed some indenting of the functions for it to work well.

files = request.files.getlist('image_name')
    for file in files:
        if file and allowed_file(file.filename):
            image_id = str(uuid.uuid4())
            filename = image_id + '.png'
            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

            # Resize Images
            _image_resize(current_app.config['UPLOAD_FOLDER'], image_id, 600, 'lg')
            _image_resize(current_app.config['UPLOAD_FOLDER'], image_id, 150, 'sm')

            get_image = RoomImages(**args)
            get_image.image_name = url_for('uploaded_file', filename=filename, _external=True)
            db.session.add(get_image)
            db.session.commit()

    return get_image

Upvotes: 1

Related Questions