Inserting JSON into postgresql from Flask-Sql Alchemy

1.6k Views Asked by At

I want to insert JSON type of data in PostgreSQL Database from flask

eg: {"a":[1,2,3] , "b":[1,2,3]}

One example for such data is Phone.no and Childrens, One person can have multiple ph.no and Childrens

In flask View


@app.route('/add', methods=['POST']) 
def addRex(): 
Name = request.form[‘name’] 
data = request.get_json(force=False, silent=False, cache=True)
p = Projects(name=name,data = data) 
db.session.add(p) 
db.session.commit()

In HTTP post method

def addData(): 
name = input ('Enter Name :') 
data = input('Enter Data :') 
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(localhost:5000/add, 
data ={'name':name}, json={'data':data}) 
if (r.status_code == 200):print(' Added Successfully!!') else:print('Already exists!') 

How can I insert such kind of data from flask into postgresql.

if Anyone can help me with my problem.

Thanks in advance

1

There are 1 best solutions below

9
On

From sqlalchemy dialect, you can select JSON for Postgres. Here is an example,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSON

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username:password@localhost:5432/db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)


class Person(db.Model):
    person_name = db.Column(db.Text, primary_key=True)
    details = db.Column(JSON)


# db.create_all() ==> for creating the db

per_1 = Person(person_name='Batman', details={"phone_no": [5, 6, 7, 8, 9], "children": {"son": [
               "Dick Grayson", "Jason Todd", "Damian Wayne", "Tim Drake"], "daughter": ['Helena Wayne']}})
db.session.add(per_1)
db.session.commit()