Skip to content

Commit v0.13

kwmccabe edited this page Apr 17, 2018 · 8 revisions

v0.13 - ItemModel, hello_orm()


Files changed (2)

File web/app/item/models.py ADDED

  • Create ItemModel class to represent rows in the db table flaskapp.item.
  • The function to_json will be used by the forthcoming api module.
  • The function __repr__ returns the "official" string representation of an object. It can return a valid statement to recreate an object with the same value(s), or it can return a <useful description>.
+from flask import url_for
+from datetime import datetime
+from .. import db
+
+
+class ItemModel(db.Model):
+    __tablename__ = 'item'
+    id         = db.Column(db.BigInteger, autoincrement=True, primary_key=True)
+    keyname    = db.Column(db.String(63), nullable=False, index=True, unique=True, default='')
+    mod_create = db.Column(db.DateTime, default=datetime.utcnow)
+
+    def to_json(self):
+        json_item = {
+            #'url': url_for('api.get_item', id=self.id),
+            'id'        : self.id,
+            'keyname'   : self.keyname,
+            'mod_create': self.mod_create,
+        }
+        return json_item
+
+    def __repr__(self):
+        return '<Item %r>' % (self.id)

File web/app/item/views.py MODIFIED

  • Create test route /hello_orm to use the new model ItemModel.
  • Get column names directly from the model.
  • Get all rows via db.session.query(ItemModel).
  • Print results to match output of /hello_db if stmt = "select * from item".
 import logging
 
-from flask import current_app, escape
+from .. import db
 from . import item
 
+from .models import ItemModel
+
 
 @item.route('/item/')
 def hello_item():
     logging.info("hello_item()")
     return 'Hello FlaskApp : Item Module'
+
+
+@item.route('/hello_orm')
+def hello_orm():
+    cols  = ItemModel.__table__.columns.keys()
+    rows = db.session.query(ItemModel)
+
+    result = '<b>db.session.query(ItemModel)</b>'
+    result += '<br/>| '
+    for col in cols:
+        result += '<b>'+str(col)+'</b> | '
+    for row in rows:
+        result += '<br/>| '
+        for col in cols:
+            result += '%s | ' % getattr( row, col )
+    return result

Commit-v0.12 | Commit-v0.13 | Commit-v0.14

Clone this wiki locally