Last active
March 11, 2017 13:38
-
-
Save sroccaserra/e5127e5511612dd899fe3662e3b56a96 to your computer and use it in GitHub Desktop.
Active Record Illustration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from mongoengine import Document, StringField, ReferenceField, CASCADE, EmbeddedDocumentField, ListField | |
| class Post(Document): | |
| title = StringField(max_length=120, required=True) | |
| author = ReferenceField(User, reverse_delete_rule=CASCADE) | |
| tags = ListField(StringField(max_length=30)) | |
| comments = ListField(EmbeddedDocumentField(Comment)) | |
| meta = {'allow_inheritance': True} | |
| class TextPost(Post): | |
| content = StringField() | |
| class ImagePost(Post): | |
| image_path = StringField() | |
| class LinkPost(Post): | |
| link_url = StringField() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Référence : PEAAP, page 162. | |
| # Note : mettre en gras les parties dépendant de la db. | |
| class Product: | |
| @classmethod | |
| find(cls, id): | |
| find_statement = cls.find_statement(id) | |
| try: | |
| row = db.findOne(find_statement) # Did you spot the gorilla? | |
| return cls.load(row) | |
| except DBException as e: | |
| # Do what you have to | |
| finally: | |
| cls.db.cleanup(find_statement) | |
| @staticmethod | |
| load(row): | |
| # And db deserialization validation? | |
| return Product( | |
| id=row[0], | |
| first_name=row[1], | |
| last_name=row[2] | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from mongoengine import Document, StringField | |
| class User(Document): | |
| email = StringField(required=True) | |
| first_name = StringField(max_length=50) | |
| last_name = StringField(max_length=50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment