in Flask, Flask-PyMongo, MongoDB, PyMongo, PYTHON, Web Development


So the concept escaped me for a couple of days. I actually had considered abandoning my MongoDB trials in favor of a SQL based system. What I discovered was that I am more persistent in finding a solution to my problem than I originally thought. I stumbled upon this Gist:

This is a very simple and basic Pagination class written for MongoEngine. Flask already has an extension for MongoEngine with this already built in. After looking at the code I realized all this is doing is passing an iterable to the Pagination class and then building links in the template. So I decided I would type it out line by line so I could get a better grasp on what was happening in the code.

So now I have Flask-PyMongo communicating with my database and was able to build the models in such a way that makes more sense to me at this stage of my learning.

For instance, my Post model looks like this:

[pastacode lang=”python” manual=”class%20Post(object)%3A%0A%0A%0A%20%20%20%20def%20__init__(self%2C%20title%2C%20content%2C%20author%2C%20created%3DNone)‘%25A%20%25x%20%40%20%25H%3A%25M%3A%25S’)%20%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20created%20is%20None%20else%20created%0A%0A%20%20%20%20def%20__repr__(self)%3A%0A%20%20%20%20%20%20%20%20return%20%22%3CPost%20%7B%7D%3E%22.format(self.title)%0A%0A%20%20%20%20def%20json(self)’title’%3A%20self.title%7D%2C%20self.json()%2C%20upsert%3DTrue)%0A” message=”” highlight=”” provider=”manual”/]

MongoEngine allows reference fields so you can actually store the author object in the post document…which is kind of cool becuase you could do something like this from the template So I was a little stuck on trying to find a way to do this using PyMongo until I read this post:¬†

It explains a more efficient way of doing this. In my case I am referencing the user by the author variable, so I have set my User class up so that _id is a unique username and will reference the user by the username.

See the User class:

[pastacode lang=”python” manual=”class%20User(object)%3A%0A%0A%20%20%20%20def%20__init__(self%2C%20_id%2C%20email%2C%20password%2C%20fullname)” message=”” highlight=”” provider=”manual”/]

So using the get_user() method I can get the fullname…

LEARNING A LOT! and having a lot of fun!

Also found this library…for generating fake data…VERY useful

Write a Comment