Bootstrap FreeKB - Flask - Update JSONB using SQLAlchemy
Flask - Update JSONB using SQLAlchemy

Updated:   |  Flask articles

If you are not familiar with SQLAlchemy, check out my article Getting Started with SQLAlchemy.

This assumes you have already setup Flask to connect to a database.

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

And let's say your Flask app has the following structure.

├── main.py
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html

 

Let's say models.py contains the following. In this example, my_table contains a JSON column.

from . import db
class my_table(db.Model):
  id        = db.Column(db.Integer, nullable=False, unique=True, primary_key=True)
  json      = db.Column(MutableDict.as_mutable(db.JSON))

 

Your HTML page would have an input form like this. Notice in this example that the name of the input is my_json.

<form method="post" action="/Results">
  <input type="text" name="my_json">
</form>

 

Here is how you could update the json column in my_table. Since the input form passes the json as a string ast is used to convert the string into a dictionary.

from flask import Blueprint, render_template
from . import db
from .models import my_table

import ast

views = Blueprint('views', __name__)

@views.route('/Results', methods=['GET', 'POST'])
def results():
  my_table = my_table.query.filter_by(id=request.form.get('id')).one()
  my_table.my_json = ast.literal_eval(request.form.get('my_json'))
  db.session.commit()
  db.session.close()
  return render_template('success.html') 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter c8d7d3 in the box below so that we can be sure you are a human.