0
votes

So I am trying to put some data into an SQLite DB using SQLAlchemy.

The JSON data I am trying to put into table:

[{'type': 'paragraph', 'children': [{'text': 'A line of text in a paragraph.'}]}]

My model:

import datetime
from . import db, ma

class Books(db.Model):

    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False) 

    def __init__(self, content):
        self.content = content

class ContentSchema(ma.Schema):
        fields = ('content')

My view:

@main_blueprint.route('/add_book', methods=['POST'])
def add_book():

    books_data = request.get_json()

    new_book = Books(content=books_data)

    db.session.add(new_book)
    db.session.commit()

    return 'Success', 201

The error I am recieving is the following:

sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type.
[SQL: INSERT INTO books (content) VALUES (?)]
[parameters: ([{'type': 'paragraph', 'children': [{'text': 'A line of text in a paragraph.'}]}],)]
(Background on this error at: http://sqlalche.me/e/rvf5)

How can I put JSON data into the database?

Thanks, Alex

1

1 Answers

0
votes

The content field expects text

books_data = request.get_json()
new_book = Books(content=books_data)

Here, it's being fed a JSON object.

import json
...
next_book = Books(content=json.dumps(books_data))

should fix that. You'll need to use json.loads() after retrieving content to reconstitute a JSON object, assuming that's what you'll need.