Home > Software engineering >  How to access the content of a single column from a flask-sqlalchemy model?
How to access the content of a single column from a flask-sqlalchemy model?

Time:10-25

I am new to flask, and I have a query pertaining flask-sqlalchemy. My program makes use of dropzone.js and so it uploads multiple images and the goal is to save the image-file urls as string list to database for access later.

I created a list and then appended the urls to that list, before typecasting that list to a string eg. str(file_urls), and adding it to the model's field like so,

foo = FooForm()
file_urls = list()

for uploaded_file in request.files.getlist('file'):
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            return "Invalid Image", 400
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        file_urls.append(filename)

if foo.validate_on_submit():
    _post = Post(image_folder=str(file_urls)) # assuming it's the only column present in the table
    db.session.add(_post)
    db.session.commit()

The view structure looks something like,

@app.route('/post/<int:some_post_id>')
def post_fn(some_post_id):
    # relevent code here

    file_urls = eval(Post.image_folder) #I get error here stating that," TypeError: eval() arg 1 must be a string, bytes or code object"

    return render_template('a_template.html', file_urls=file_urls)

Model :

class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_folder = db.Column(db.String(120), nullable=False)

def __repr__(self):
    return '{}'.format(self.image_folder)

In a such context, how would one go about retrieving the string stored in the variable image_folder, in order to convert it into a list again using eval?

Anyone please?

CodePudding user response:

Depending on how your Model is setup, you would have to do something like this:

@app.route('/post/<int:some_post_id>')
def post_fn(some_post_id):
    # irrelevent code here
    post = Post.query.filter_by(id=id) # Get the post from the database with the id from the route
    file_urls = eval(post.image_folder) 

    return render_template('a_template.html', file_urls=file_urls)
  • Related