Some tips on how to use Flask with MongoDB to build a REST Backend for Backbone/Brunch/Chaplin.
With both these tools, it’s extremely easy to build a full featured REST Backend ready to use with Backbone Models/Collections. I hope these tips will help you avoid some pitfalls I’ve fallen into.
Set Backbone Model idAttribute to _id
By default Backbone expects an
id key, but MongoDB use an
_id key, so you have to change the default id attribute.
You can check the Backbone documentation on the idAttribute.
1 2 3
You can also make the change globally:
If you forget to do this, when updating a model, Backbone will make a POST request instead of a PUT request because the
id attribute won’t be set.
Serve the index file with render_template
I use the backbone project index file as a flask template, and render it using
render_template so it’s possible to use flask
session object and make link to custom flask view.
1 2 3
If you use a tool like Brunch to build your backbone application, you might have an additional public directory, and if you want to use
render_template with the index.html file, here is a way to make the folder available for flask:
1 2 3 4 5 6 7 8 9 10
Flask has a little helper jsonify that create a Response object with a json mimetype, it makes use of simplejson or the default python json module.
1 2 3
Since jsonify “acts like a python dict”, you must return something like
jsonify(**mydict), so you must define a parse function in your backbone Collections
1 2 3
Also, with MongoDB Document,
jsonify will throw an
TypeError exception saying that
Datetime is not JSON serializable, so I cast them to string using a custom JSONEncoder and a custom
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Here is how I typically handle authentication in a flask/backbone application.
First, Flask handle everything (user status stored in flask session, login, logout…), see Flask Quickstart on Sessions for a basic user authentication example, and if you are looking for a secure way to store user password, I recommend you to read this excellent article on how to store password securely using python-bcrypt.
Then, for every request (user/ajax request) I check user authentication using two differents Flask View Decorator. One for ajax request that send a 401 status code and the other for user page, that redirect to the login page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
I randomly discovered flask MethodView and keep using it to deal with Backbone Model/Collection. If you haven’t read the doc on flask view, you should read it.
Here is a simple and not secure example (In the real world, I use Schematics formerly dictshield to validate data).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Don’t forget that when using a MethodView, you have to decorate view by hand.
That’s all. Please, don’t hesitate if you have any suggestions or tips !