Home > Enterprise >  Cannot POST a JSON object to Database using Flask Python
Cannot POST a JSON object to Database using Flask Python

Time:06-07

I'm trying to post and get objects using Flask but I keep getting sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: object.

I tried doing POST into http://127.0.0.1/data and the json I provided is

{
    "oid": "123456789",
    "size": "1234"
}

Below is my code

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)

class Object(db.Model):
    oid = db.Column(db.Integer, primary_key=True)
    size = db.Column(db.Integer)

    def __repr__(self):
        return f'Object: {self.oid}, Size: {self.size}'

@app.route('/')
def index():
    return 'DSAP_2022'

@app.route('/data/<oid>', methods=['GET'])
def getObject(oid):
    obj = Object.query.filter_by(oid=oid).first()
    if obj is None:
        return 'Object not found', 404
    return repr(obj)

@app.route('/data', methods=['POST'])
def putObject():
    obj = Object(oid=request.json['oid'], size=request.json['size'])
    db.session.add(obj)
    db.session.commit()
    return 'OK'

if __name__ == '__main__':
    app.run()

I am using Postman to submit my requests. and the index() works, however, both getObject and putObject doest not work because of the same error.

CodePudding user response:

You're never calling db.create_all() to create the database tables. You would need something like:

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)

class Object(db.Model):
    oid = db.Column(db.Integer, primary_key=True)
    size = db.Column(db.Integer)

    def __repr__(self):
        return f'Object: {self.oid}, Size: {self.size}'

# Create tables corresponding to sqlalchemy models
db.create_all()

@app.route('/')
def index():
    return 'DSAP_2022'

@app.route('/data/<oid>', methods=['GET'])
def getObject(oid):
    obj = Object.query.filter_by(oid=oid).first()
    if obj is None:
        return 'Object not found', 404
    return repr(obj)

@app.route('/data', methods=['POST'])
def putObject():
    obj = Object(oid=request.json['oid'], size=request.json['size'])
    db.session.add(obj)
    db.session.commit()
    return 'OK'

if __name__ == '__main__':
    app.run()

  • Related