0

Below is an example of what I'm trying to achieve but I keep getting an error. sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: object

basically i'm trying to PUT a data that has oid, and size. and then being able to GET it.

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy

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

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

    def __repr__(self):
        return '<Object %r, Size: %r>' % self.oid % self.size

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

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

@app.route('/data/<repository>', methods=['PUT'])
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(debug=True)

what am I doing wrong here?

Joey Joestar
  • 205
  • 1
  • 11
  • I get `TypeError: putObject() got an unexpected keyword argument 'repository'`. Please post working code and the entire stacktrace, this will improve the quality of answers. – Michael Ruth Jun 06 '22 at 22:33
  • Does this answer your question? [sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table](https://stackoverflow.com/questions/44941757/sqlalchemy-exc-operationalerror-sqlite3-operationalerror-no-such-table) – Michael Ruth Jun 06 '22 at 22:35
  • The next thing you're doing wrong is the format string in `getObject()`. The right hand side takes a tuple, it doesn't append. It should be `'Object %r, Size: %r' % (obj.oid, obj.size)`. But, seriously, you're using Python 3, prefer f-string over %: `f'Object {obj.oid}, Size: {obj.size}'`. Or better yet, fix `Object.__repr__()` and return `repr(obj)` from `getObject()`. – Michael Ruth Jun 06 '22 at 22:44
  • Note that PUT is usually used for updates rather than creation. POST is usually used for creation. The code will still work with PUT but in this case PUT isn't idempotent. https://stackoverflow.com/questions/630453/what-is-the-difference-between-post-and-put-in-http – Michael Ruth Jun 06 '22 at 22:50
  • @MichaelRuth, why wouldn't PUT be idempotent in this case? – Joey Joestar Jun 06 '22 at 23:25
  • Oh hey, it is idempotent here because the requester supplies the oid – Michael Ruth Jun 08 '22 at 16:07

0 Answers0