Flask's RESTful interface and serialization

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

+4
source share
2 answers

I would use a module for this, to be honest. We used Flask-Restless for some APIs, you can take a look at this:

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

However, if you want to create your own, you can use SQLAlchemy 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 need to check three times that I understand the syntax correctly, 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 that could help you more. I am familiar with SQLAlchemy 0.7, and it seems like 0.8 has added some more convenient introspection methods:

SQLAlchemy Preview

+7
source

The checkbox provides a jsonify function to do this. Check out his work here .

Your json_dump method is correct, although the code can be concise. See This Code Snippet

 @app.route('/tasks') def tasks(): tasks = Tasks.query.all() return jsonify(data=[c.json_dump() for c in tasks]) 
-1
source

Source: https://habr.com/ru/post/1448067/


All Articles