Categories
Python Answers

How to insert many-to-many data with Python Flask and SQLAlchemy?

Sometimes, we want to insert many-to-many data with Python Flask and SQLAlchemy.

In this article, we’ll look at how to insert many-to-many data with Python Flask and SQLAlchemy.

How to insert many-to-many data with Python Flask and SQLAlchemy?

To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.

For instance, we write

association_table = db.Table('association', db.Model.metadata,
    db.Column('left_id', db.Integer, db.ForeignKey('left.id')),
    db.Column('right_id', db.Integer, db.ForeignKey('right.id'))
)

class Parent(db.Model):
    __tablename__ = 'left'
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship("Child",
                    secondary=association_table)

class Child(db.Model):
    __tablename__ = 'right'
    id = db.Column(db.Integer, primary_key=True)


p = Parent()
c = Child()
p.children.append(c)
db.session.add(p)
db.session.commit()

to create the association_table that creates a many to many relationship between Parent and Child.

Then we create a Parent and Child instance with

p = Parent()
c = Child()

Next, we create a link between p and c with

p.children.append(c)

Then we commit the operation with

db.session.add(p)
db.session.commit()

Conclusion

To insert many-to-many data with Python Flask and SQLAlchemy, we can append the data with append.

Categories
Python Answers

How to cast Python Flask form value to int?

Sometimes, we want to cast Python Flask form value to int.

In this article, we’ll look at how to cast Python Flask form value to int.

How to cast Python Flask form value to int?

To cast Python Flask form value to int, we can use the int function.

For instance, we write

personId = int(request.form['personId'])

to call int with the input value of the field with name personId into an integer.

We can also call request.form.get with the type argument to do the same thing.

For instance, we write

personId = request.form.get('personId', type=int)

to get the same input field value and convert it to an int by setting the type argument to int.

Conclusion

To cast Python Flask form value to int, we can use the int function.

Categories
Python Answers

How to get the root path of a Python Flask application?

Sometimes, we want to get the root path of a Python Flask application.

In this article, we’ll look at how to get the root path of a Python Flask application.

How to get the root path of a Python Flask application?

To get the root path of a Python Flask application, we can use the app.instance_path property.

For instance, we write

filename = os.path.join(app.instance_path, 'my_folder', 'my_file.txt')

to get the Flask app instance’s folder with app.instance_path.

Conclusion

To get the root path of a Python Flask application, we can use the app.instance_path property.

Categories
Python Answers

How to upload an image in Python Flask?

Sometimes, we want to upload an image in Python Flask.

In this article, we’ll look at how to upload an image in Python Flask.

How to upload an image in Python Flask?

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.

For instance, we write

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

to get the uploaded file from the form data entry with key file with

file = request.files['file']

We check if the file isn’t selected with

if file.filename == ''

Then we save the file to disk with

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

Conclusion

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.

Categories
Python Answers

How to jsonify a list of objects with Python Flask?

Sometimes, we want to jsonify a list of objects with Python Flask.

In this article, we’ll look at how to jsonify a list of objects with Python Flask.

How to jsonify a list of objects with Python Flask?

To jsonify a list of objects with Python Flask, we add a method in our object’s class to return the object’s contents as a dictionary.

For instance, we write

class Gene(object):
    #...

    def serialize(self):
        return {
            'gene_id': self.gene_id, 
            'gene_symbol': self.gene_symbol,
            'p_value': self.p_value,
        }

to create the Gene class that has the serialize method that returns the instance properties in a dictionary.

Then we call serialize to return the dictionaries by and put them in a list by writing.

jsonify(eqtls=[e.serialize() for e in my_list_of_eqtls])

where e is a Gene instance in the my_list_of_eqtls list.

We call jsonify with the list set as the value of the eqtls argument to return a JSON response with the list of dicts.

Conclusion

To jsonify a list of objects with Python Flask, we add a method in our object’s class to return the object’s contents as a dictionary.