I am learning Backbone.js and Flask (and Flask-sqlalchemy). I chose Flask because I read that it works well with Backbone that implements RESTful interfaces. I am 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 the json_dump method 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 are not, but overall it is not as simple as I expected.
After a while, I got 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, this seems a bit detailed. Again, what is the correct way to implement them? I saw some extensions that offer RESTful interfaces in Flask, but they look pretty complicated for me.
thanks