Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful interface in Flask and issues serializing

I'm learning Backbone.js and Flask (and Flask-sqlalchemy). I chose Flask because I read that it plays well with Backbone implementing RESTful interfaces. I'm currently following a course that uses (more or less) this model:

class Tasks(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), unique=True)
    completed = db.Column(db.Boolean, unique=False, default=False)

    def __init__(self, title, completed):
        self.title = title
        self.completed = completed

    def json_dump(self):
        return dict(title=self.title, completed=self.completed)

    def __repr__(self):
        return '<Task %r>' % self.title

I had to add a json_dump method in order to send JSON to the browser. Otherwise, I would get errors like object is not JSON serializable, so my first question is:

Is there a better way to do serialization in Flask? It seems that some objects are serializable but others aren't, but in general, it's not as easy as I expected.

After a while, I ended up with the following views to take care of each type of request:

@app.route('/tasks')
def tasks():
    tasks = Tasks.query.all()
    serialized = json.dumps([c.json_dump() for c in tasks])
    return serialized

@app.route('/tasks/<id>', methods=['GET'])
def get_task(id):
    tasks = Tasks.query.get(int(id))
    serialized = json.dumps(tasks.json_dump())
    return serialized

@app.route('/tasks/<id>', methods=['PUT'])
def put_task(id):
    task = Tasks.query.get(int(id))
    task.title = request.json['title']
    task.completed = request.json['completed']
    db.session.add(task)
    db.session.commit()
    serialized = json.dumps(task.json_dump())
    return serialized

@app.route('/tasks/<id>', methods=['DELETE'])
def delete_task(id):
    task = Tasks.query.get(int(id))
    db.session.delete(task)
    db.session.commit()
    serialized = json.dumps(task.json_dump())
    return serialized

@app.route('/tasks', methods=['POST'])
def post_task():
    task = Tasks(request.json['title'], request.json['completed'])
    db.session.add(task)
    db.session.commit()
    serialized = json.dumps(task.json_dump())
    return serialized

In my opinion, it seems a bit verbose. Again, what is the proper way to implement them? I have seen some extensions that offer RESTful interfaces in Flask but those look quite complex to me.

Thanks

like image 617
Robert Smith Avatar asked Nov 24 '12 06:11

Robert Smith


People also ask

Is Flask a RESTful API?

"Flask allows Python developers to create lightweight RESTful APIs."

What is the difference between flask and flask RESTful?

Flask is a highly flexible Python web framework built with a small core and easy-to-extend philosophy. Flask-Restful is an extension of Flask that offers extension to enable writing a clean object-oriented code for fast API development.

What is serialization in flask?

Serialization is a process of converting complex python objects into flat structure consisting of only native python datatypes.


1 Answers

I would use a module to do this, honestly. We've used Flask-Restless for some APIs, you might take a look at that:

https://flask-restless.readthedocs.org/en/latest/

However, if you want build your own, you can use SQLAlchemy's introspection to output your objects as key/value pairs.

http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#metadata-reflection

Something like this, although I always have to triple-check I got the syntax right, so take this as a guide more than working code.

@app.route('/tasks')
def tasks():
    tasks = Tasks.query.all()

    output = []
    for task in tasks:
      row = {}

      for field in Tasks.__table__.c:
        row[str(field)] = getattr(task, field, None)

      output.append(row)

    return jsonify(data=output)

I found this question which might help you more. I'm familiar with SQLAlchemy 0.7 and it looks like 0.8 added some nicer introspection techniques:

SQLAlchemy introspection

like image 174
Rachel Sanders Avatar answered Oct 08 '22 05:10

Rachel Sanders