From ff3369dd1b85742a9c3d0508c5e5c31e14f4220d Mon Sep 17 00:00:00 2001
From: Aurélien Bompard <aurelien@bompard.org>
Date: Feb 05 2017 11:01:11 +0000
Subject: Use SQLA's query_attribute, it saves a lot of passing around


---

diff --git a/delete-user.py b/delete-user.py
index 42a17c1..8c54582 100755
--- a/delete-user.py
+++ b/delete-user.py
@@ -18,14 +18,14 @@ session = hubs.models.init(fedmsg_config['hubs.sqlalchemy.uri'])
 username = raw_input('What user do you want to delete: ')
 openid = '%s.id.fedoraproject.org' % username
 print "Looking for account %r" % openid
-user = hubs.models.User.get(session, openid)
+user = hubs.models.User.get(openid)
 if not user:
     print "No such user %r" % openid
 else:
     print "Found %r.  Deleting." % user
     session.delete(user)
 
-hub = hubs.models.Hub.get(session, username)
+hub = hubs.models.Hub.get(username)
 if not hub:
     print "No such hub %r" % username
 else:
diff --git a/hubs/app.py b/hubs/app.py
index 006edea..702175a 100755
--- a/hubs/app.py
+++ b/hubs/app.py
@@ -99,7 +99,7 @@ def check_auth():
             flask.session.auth.avatar=username2avatar(
                 flask.session.auth.nickname)
             flask.session.auth.user = hubs.models.User.by_username(
-                session, flask.session.auth.nickname)
+                flask.session.auth.nickname)
         flask.g.auth = flask.session.auth
     else:
         flask.g.auth = munch.Munch(logged_in=False)
diff --git a/hubs/backend/worker.py b/hubs/backend/worker.py
index abc1b32..b4af706 100755
--- a/hubs/backend/worker.py
+++ b/hubs/backend/worker.py
@@ -46,7 +46,7 @@ log = logging.getLogger('hubs.backend.worker')
 
 def work(session, widget_idx):
     # Get a real widget, because we update last_refreshed on it.
-    widget = hubs.models.Widget.by_idx(session, widget_idx)
+    widget = hubs.models.Widget.by_idx(widget_idx)
     log.info("! Invalidating cache for %r" % widget)
     # Invalidate the cache...
     hubs.widgets.base.invalidate_cache(widget, **widget.config)
diff --git a/hubs/models.py b/hubs/models.py
index cdc02de..63fbcb1 100755
--- a/hubs/models.py
+++ b/hubs/models.py
@@ -37,6 +37,7 @@ from sqlalchemy.orm import sessionmaker
 from sqlalchemy.orm import scoped_session
 from sqlalchemy.orm import relation
 from sqlalchemy.orm import backref
+from sqlalchemy.orm.session import object_session
 
 import fedmsg
 import fedmsg.utils
@@ -91,8 +92,9 @@ def init(db_url, debug=False, create=False):
 
     if create:
         BASE.metadata.create_all(engine)
-
-    return scoped_session(sessionmaker(bind=engine))
+    session = scoped_session(sessionmaker(bind=engine))
+    BASE.query = session.query_property()
+    return session
 
 
 roles = ['subscriber', 'member', 'owner', 'stargazer']
@@ -113,8 +115,8 @@ class Association(BASE):
     hub = relation("Hub", backref=backref('associations', cascade="all, delete"))
 
     @classmethod
-    def get(cls, session, hub, user, role):
-        return session.query(cls)\
+    def get(cls, hub, user, role):
+        return cls.query\
             .filter_by(hub=hub)\
             .filter_by(user=user)\
             .filter_by(role=role)\
@@ -164,7 +166,7 @@ class Hub(BASE):
 
     @classmethod
     def get_or_create(cls, session, name, summary, **extra):
-        self = cls.by_name(session, name)
+        self = cls.by_name(name)
         if not self:
             self = cls.create_group_hub(session, name, summary, **extra)
             session.add(self)
@@ -191,20 +193,22 @@ class Hub(BASE):
         return [assoc.user for assoc in self.associations
                 if assoc.role == 'stargazer']
 
-    def subscribe(self, session, user, role='subscriber'):
+    def subscribe(self, user, role='subscriber'):
         """ Subscribe a user to this hub. """
         # TODO -- add logic here to manage not adding the user multiple
         # times, doing different roles, etc.. publish a fedmsg message,
         # etc...
+        session = object_session(self)
         session.add(Association(user=user, hub=self, role=role))
         session.commit()
 
-    def unsubscribe(self, session, user, role='subscriber'):
+    def unsubscribe(self, user, role='subscriber'):
         """ Subscribe a user to this hub. """
         # TODO -- add logic here to manage not adding the user multiple
         # times, doing different roles, etc.. publish a fedmsg message,
         # etc...
-        association = Association.get(session, hub=self, user=user, role=role)
+        session = object_session(self)
+        association = Association.get(hub=self, user=user, role=role)
         if not association:
             raise KeyError("%r is not a %r of %r" % (user, role, self))
         session.delete(association)
@@ -214,18 +218,18 @@ class Hub(BASE):
         return user in self.owners
 
     @classmethod
-    def by_name(cls, session, name):
-        return session.query(cls).filter_by(name=name).first()
+    def by_name(cls, name):
+        return cls.query.filter_by(name=name).first()
 
     get = by_name
 
     @classmethod
-    def all_group_hubs(cls, session):
-        return session.query(cls).filter_by(user_hub=False).all()
+    def all_group_hubs(cls):
+        return cls.query.filter_by(user_hub=False).all()
 
     @classmethod
-    def all_user_hubs(cls, session):
-        return session.query(cls).filter_by(user_hub=True).all()
+    def all_user_hubs(cls):
+        return cls.query.filter_by(user_hub=True).all()
 
     @classmethod
     def create_user_hub(cls, session, username, fullname):
@@ -236,8 +240,8 @@ class Hub(BASE):
 
         hubs.defaults.add_user_widgets(session, hub, username, fullname)
 
-        user = User.by_username(session, username)
-        hub.subscribe(session, user, role='owner')
+        user = User.by_username(username)
+        hub.subscribe(user, role='owner')
         return hub
 
     @classmethod
@@ -272,7 +276,7 @@ class Hub(BASE):
         """Returns the list of indices for this hub's widgets."""
         return [w.idx for w in self.widgets]
 
-    def __json__(self, session):
+    def __json__(self):
         return {
             'name': self.name,
             'summary': self.summary,
@@ -306,16 +310,16 @@ class Widget(BASE):
     left = sa.Column(sa.Boolean, nullable=False, default=False)
 
     @classmethod
-    def by_idx(cls, session, idx):
-        return session.query(cls).filter_by(idx=idx).first()
+    def by_idx(cls, idx):
+        return cls.query.filter_by(idx=idx).first()
 
     @classmethod
-    def by_plugin(cls, session, plugin):
-        return session.query(cls).filter_by(plugin=plugin).first()
+    def by_plugin(cls, plugin):
+        return cls.query.filter_by(plugin=plugin).first()
 
     @classmethod
-    def by_hub_id_all(cls, session, hub_id):
-        return session.query(cls).filter_by(hub_id=hub_id).all()
+    def by_hub_id_all(cls, hub_id):
+        return cls.query.filter_by(hub_id=hub_id).all()
 
     get = by_idx
 
@@ -327,7 +331,8 @@ class Widget(BASE):
     def config(self, config):
         self._config = json.dumps(config)
 
-    def __json__(self, session):
+    def __json__(self):
+        session = object_session(self)
         module = hubs.widgets.registry[self.plugin]
         data = module.data(session, self, **self.config)
         data.pop('widget', None)
@@ -350,7 +355,8 @@ class Widget(BASE):
     def module(self):
         return hubs.widgets.registry[self.plugin]
 
-    def render(self, session):
+    def render(self):
+        session = object_session(self)
         render = hubs.widgets.render
         return render(self.module, session, self, **self.config)
 
@@ -363,7 +369,7 @@ class User(BASE):
     saved_notifications = relation('SavedNotification', backref='users',
                                        lazy='dynamic')
 
-    def __json__(self, session):
+    def __json__(self):
         return {
             'username': self.username,
             'avatar': username2avatar(self.username),
@@ -405,25 +411,25 @@ class User(BASE):
         ])), key=operator.attrgetter('name'))
 
     @classmethod
-    def by_username(cls, session, username):
-        return session.query(cls).filter_by(username=username).first()
+    def by_username(cls, username):
+        return cls.query.filter_by(username=username).first()
 
     get = by_username
 
     @classmethod
-    def all(cls, session):
-        return session.query(cls).all()
+    def all(cls):
+        return cls.query.all()
 
     @classmethod
     def get_or_create(cls, session, username, fullname):
         if not username:
             raise ValueError("Must provide an username, not %r" % username)
 
-        self = cls.by_username(session, username)
+        self = cls.by_username(username)
         if not self:
             self = cls(username=username, fullname=fullname)
             session.add(self)
-            if not Hub.by_name(session, self.username):
+            if not Hub.by_name(self.username):
                 Hub.create_user_hub(session, self.username, self.fullname)
 
             session.commit()
@@ -446,12 +452,12 @@ class VisitCounter(BASE):
     hub = relation("Hub", backref=backref('visit_counters', cascade="all, delete, delete-orphan"))
 
     @classmethod
-    def by_username(cls, session, username):
-        return session.query(cls).filter_by(username=username).all()
+    def by_username(cls, username):
+        return cls.query.filter_by(username=username).all()
 
     @classmethod
-    def get_visits_by_username_hub(cls, session, username, visited_hub):
-        return session.query(cls).filter_by(username=username, visited_hub=visited_hub).first()
+    def get_visits_by_username_hub(cls, username, visited_hub):
+        return cls.query.filter_by(username=username, visited_hub=visited_hub).first()
 
     @classmethod
     def increment_visits(cls, session, username, visited_hub):
@@ -480,7 +486,7 @@ class VisitCounter(BASE):
                 or not cls._does_user_exist(session, user=username):
             raise ValueError("Must provide a hub/user that exists")
 
-        self = cls.get_visits_by_username_hub(session, username=username,
+        self = cls.get_visits_by_username_hub(username=username,
                                               visited_hub=visited_hub)
         if not self:
             self = cls(username=username, visited_hub=visited_hub)
@@ -521,9 +527,9 @@ class SavedNotification(BASE):
         }
 
     @classmethod
-    def by_username(cls, session, username):
-        return session.query(cls).filter_by(user=username).all()
+    def by_username(cls, username):
+        return cls.query.filter_by(user=username).all()
 
     @classmethod
-    def all(cls, session):
-        return session.query(cls).all()
+    def all(cls):
+        return cls.query.all()
diff --git a/hubs/tests/__init__.py b/hubs/tests/__init__.py
index b1e182f..59866ee 100644
--- a/hubs/tests/__init__.py
+++ b/hubs/tests/__init__.py
@@ -58,7 +58,7 @@ class APPTest(unittest.TestCase):
 
         hubs.app.session.flush()
 
-        hub = hubs.models.Hub.by_name(hubs.app.session, 'ralph')
+        hub = hubs.models.Hub.by_name('ralph')
         widget = hubs.models.Widget(
             plugin='about',
             index=500,
@@ -82,7 +82,7 @@ class APPTest(unittest.TestCase):
     # TODO - test that it has all the things it needs
 
     def widget_instance(self, hubname, plugin):
-        hub = hubs.models.Hub.by_name(self.session, hubname)
+        hub = hubs.models.Hub.by_name(hubname)
         if not hub:
             raise ValueError("No such hub %r" % hubname)
         for widget in hub.widgets:
diff --git a/hubs/tests/test_api/test_hub.py b/hubs/tests/test_api/test_hub.py
index 821746c..622fd9d 100644
--- a/hubs/tests/test_api/test_hub.py
+++ b/hubs/tests/test_api/test_hub.py
@@ -16,20 +16,20 @@ class TestHubSubscribe(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_subscribe_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/subscribe'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_subscribe_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         with hubs.tests.auth_set(app, self.user):
             resp = self.app.post('/api/hub/{}/subscribe'.format(hub.name),
                                  follow_redirects=True)
             self.assertEqual(resp.status_code, 200)
             # Need to find the Hub again to avoid DetachedInstanceError
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username in usernames(h.subscribers))
 
 
@@ -37,17 +37,17 @@ class TestHubUnsubscribe(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_unsubscribe_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/unsubscribe'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_unsubscribe_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         # Need a real user model to subscribe to the hub
-        User = hubs.models.User.by_username(self.session, self.user.username)
-        hub.subscribe(self.session, User)
+        User = hubs.models.User.by_username(self.user.username)
+        hub.subscribe(User)
 
         self.assertTrue(self.user.username in usernames(hub.subscribers))
 
@@ -55,7 +55,7 @@ class TestHubUnsubscribe(hubs.tests.APPTest):
             resp = self.app.post('/api/hub/{}/unsubscribe'.format(hub.name),
                                  follow_redirects=True)
             self.assertEqual(resp.status_code, 200)
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username not in usernames(h.subscribers))
 
 
@@ -63,20 +63,20 @@ class TestHubStar(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_star_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/star'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_star_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         with hubs.tests.auth_set(app, self.user):
             resp = self.app.post('/api/hub/{}/star'.format(hub.name),
                                  follow_redirects=True)
 
             self.assertEqual(resp.status_code, 200)
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username in usernames(h.stargazers))
 
 
@@ -84,17 +84,17 @@ class TestHubUnstar(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_unstar_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/unstar'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_unstar_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         # Need a real user model to subscribe to the hub
-        User = hubs.models.User.by_username(self.session, self.user.username)
-        hub.subscribe(self.session, User, role='stargazer')
+        User = hubs.models.User.by_username(self.user.username)
+        hub.subscribe(User, role='stargazer')
 
         self.assertTrue(self.user.username in [u.username for
                                                u in hub.stargazers])
@@ -103,7 +103,7 @@ class TestHubUnstar(hubs.tests.APPTest):
             resp = self.app.post('/api/hub/{}/unstar'.format(hub.name),
                                  follow_redirects=True)
             self.assertEqual(resp.status_code, 200)
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username not in usernames(h.stargazers))
 
 
@@ -111,20 +111,20 @@ class TestHubJoin(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_join_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/join'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_join_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         with hubs.tests.auth_set(app, self.user):
             resp = self.app.post('/api/hub/{}/join'.format(hub.name),
                                  follow_redirects=True)
 
             self.assertEqual(resp.status_code, 200)
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username in usernames(h.members))
 
 
@@ -132,22 +132,22 @@ class TestHubLeave(hubs.tests.APPTest):
     user = hubs.tests.FakeAuthorization('decause')
 
     def test_leave_redirects_when_logged_out(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         resp = self.app.post('/api/hub/{}/leave'.format(hub.name),
                              follow_redirects=False)
         self.assertEqual(resp.status_code, 302)
         self.assertEqual(urlparse(resp.location).path, '/login')
 
     def test_star_when_logged_in(self):
-        hub = hubs.models.Hub.by_name(self.session, 'infra')
+        hub = hubs.models.Hub.by_name('infra')
         # Need a real user model to subscribe to the hub
-        User = hubs.models.User.by_username(self.session, self.user.username)
-        hub.subscribe(self.session, User, role='member')
+        User = hubs.models.User.by_username(self.user.username)
+        hub.subscribe(User, role='member')
 
         with hubs.tests.auth_set(app, self.user):
             resp = self.app.post('/api/hub/{}/leave'.format(hub.name),
                                  follow_redirects=True)
 
             self.assertEqual(resp.status_code, 200)
-            h = hubs.models.Hub.by_name(self.session, 'infra')
+            h = hubs.models.Hub.by_name('infra')
             self.assertTrue(self.user.username not in usernames(h.members))
diff --git a/hubs/tests/test_api/test_notifications.py b/hubs/tests/test_api/test_notifications.py
index 5b8ad9e..c9c7657 100644
--- a/hubs/tests/test_api/test_notifications.py
+++ b/hubs/tests/test_api/test_notifications.py
@@ -80,7 +80,7 @@ class TestPostNotifications(hubs.tests.APPTest):
         self.assertEqual(notification['link'], 'baz')
 
         all_saved = hubs.models.SavedNotification.by_username(
-            hubs.app.session, self.user.username)
+            self.user.username)
         self.assertEqual(len(all_saved), 2)
         all_saved = [s.__json__() for s in all_saved]
         self.assertTrue(any(str(s['markup']) == self.valid_payload['markup']
diff --git a/hubs/tests/test_models.py b/hubs/tests/test_models.py
index 3065cfb..deeb258 100644
--- a/hubs/tests/test_models.py
+++ b/hubs/tests/test_models.py
@@ -12,83 +12,83 @@ class ModelTest(hubs.tests.APPTest):
     def test_delete_user(self):
         # verify user exists
         username = 'ralph'
-        user = hubs.models.User.get(self.session, username)
+        user = hubs.models.User.get(username)
         self.assertIsNotNone(user)
 
         # check if association exists
-        hub = hubs.models.Hub.get(self.session, username)
-        assoc = hubs.models.Association.get(self.session, hub, user, 'owner')
+        hub = hubs.models.Hub.get(username)
+        assoc = hubs.models.Association.get(hub, user, 'owner')
         self.assertIsNotNone(assoc)
 
         # delete the user
         self.session.delete(user)
-        user = hubs.models.User.get(self.session, username)
+        user = hubs.models.User.get(username)
         self.assertIsNone(user)
 
         # checking to see if the hub is still intact
-        hub = hubs.models.Hub.get(self.session, username)
+        hub = hubs.models.Hub.get(username)
         self.assertIsNotNone(hub)
         self.assertEqual('ralph', hub.name)
 
         # check if widgets still are intact
-        widgets = hubs.models.Widget.by_hub_id_all(self.session, hub.name)
+        widgets = hubs.models.Widget.by_hub_id_all(hub.name)
         self.assertEqual(12, len(widgets))
 
     def test_delete_hubs(self):
         # verify the hub exists
         hub_name = 'ralph'
-        hub = hubs.models.Hub.get(self.session, hub_name)
+        hub = hubs.models.Hub.get(hub_name)
         self.assertIsNotNone(hub)
 
         # check if association exists
         username = 'ralph'
-        user = hubs.models.User.get(self.session, username)
-        assoc = hubs.models.Association.get(self.session, hub, user, 'owner')
+        user = hubs.models.User.get(username)
+        assoc = hubs.models.Association.get(hub, user, 'owner')
         self.assertIsNotNone(assoc)
 
         # check if widgets exist
-        widgets = hubs.models.Widget.by_hub_id_all(self.session, hub.name)
+        widgets = hubs.models.Widget.by_hub_id_all(hub.name)
         self.assertEqual(12, len(widgets))
 
         # delete the hub
         self.session.delete(hub)
 
         # check if association is removed
-        assoc = hubs.models.Association.get(self.session, hub, user, 'owner')
+        assoc = hubs.models.Association.get(hub, user, 'owner')
         self.assertIsNone(assoc)
 
         # check if widgets are removed
-        widgets = hubs.models.Widget.by_hub_id_all(self.session, hub.name)
+        widgets = hubs.models.Widget.by_hub_id_all(hub.name)
         self.assertEqual([], widgets)
 
         # verify hub is deleted
-        hub = hubs.models.Hub.get(self.session, hub_name)
+        hub = hubs.models.Hub.get(hub_name)
         self.assertIsNone(hub)
 
         # check if user is still intact
-        user = hubs.models.User.get(self.session, username)
+        user = hubs.models.User.get(username)
         self.assertIsNotNone(user)
         self.assertEqual('ralph', user.username)
 
     def test_delete_user_then_hubs(self):
         username = 'ralph'
-        user = hubs.models.User.get(self.session, username)
+        user = hubs.models.User.get(username)
         self.assertIsNotNone(user)
         self.session.delete(user)
-        user = hubs.models.User.get(self.session, username)
+        user = hubs.models.User.get(username)
         self.assertIsNone(user)
 
         # checking to see if the hub is still intact
-        hub = hubs.models.Hub.get(self.session, username)
+        hub = hubs.models.Hub.get(username)
         self.assertIsNotNone(hub)
 
         self.session.delete(hub)
 
         # check if widgets are removed
-        widgets = hubs.models.Widget.by_hub_id_all(self.session, hub.name)
+        widgets = hubs.models.Widget.by_hub_id_all(hub.name)
         self.assertEqual([], widgets)
 
-        hub = hubs.models.Hub.get(self.session, username)
+        hub = hubs.models.Hub.get(username)
         self.assertIsNone(hub)
 
     def test_visit_counter(self):
@@ -96,7 +96,7 @@ class ModelTest(hubs.tests.APPTest):
         hub = 'decause'
         # Make sure the table is empty of data
         vc = hubs.models.VisitCounter.get_visits_by_username_hub(
-            session=self.session, username=username, visited_hub=hub)
+            username=username, visited_hub=hub)
         self.assertIsNone(vc)
 
         # Insert a new counter row
@@ -114,19 +114,17 @@ class ModelTest(hubs.tests.APPTest):
         vc = hubs.models.VisitCounter.get_or_create(
             session=self.session, username=username, visited_hub=hub)
         self.session.delete(vc)
-        hub_obj = hubs.models.Hub.get(self.session, username)
+        hub_obj = hubs.models.Hub.get(username)
         self.assertIsNotNone(hub_obj)
-        user_obj = hubs.models.User.get(session=self.session,
-                                        username=username)
+        user_obj = hubs.models.User.get(username=username)
         self.assertIsNotNone(user_obj)
 
         # Delete hub and make sure the visit counter is 0
         vc = hubs.models.VisitCounter.get_visits_by_username_hub(
-            session=self.session, username=username, visited_hub=hub)
+            username=username, visited_hub=hub)
         self.session.delete(hub_obj)
         self.assertIsNone(vc)
-        user_obj = hubs.models.User.get(session=self.session,
-                                        username=username)
+        user_obj = hubs.models.User.get(username=username)
         self.assertIsNotNone(user_obj)
 
     def test_visit_counter_does_not_exist(self):
diff --git a/hubs/tests/test_widgets/__init__.py b/hubs/tests/test_widgets/__init__.py
index 47a2f4f..229d620 100644
--- a/hubs/tests/test_widgets/__init__.py
+++ b/hubs/tests/test_widgets/__init__.py
@@ -44,7 +44,7 @@ class WidgetTest(unittest.TestCase):
 
         hubs.app.session.flush()
 
-        hub = hubs.models.Hub.by_name(hubs.app.session, 'ralph')
+        hub = hubs.models.Hub.by_name('ralph')
         widget = hubs.models.Widget(
             plugin='about',
             index=500,
@@ -75,7 +75,7 @@ class WidgetTest(unittest.TestCase):
     # TODO - test that it has all the things it needs
 
     def widget_instance(self, hubname, plugin):
-        hub = hubs.models.Hub.by_name(self.session, hubname)
+        hub = hubs.models.Hub.by_name(hubname)
         if not hub:
             raise ValueError("No such hub %r" % hubname)
         for widget in hub.widgets:
diff --git a/hubs/validators.py b/hubs/validators.py
index 302b0e7..bd5b3f2 100755
--- a/hubs/validators.py
+++ b/hubs/validators.py
@@ -25,7 +25,7 @@ def link(session, value):
 
 
 def username(session, value):
-    if hubs.models.User.by_username(session, value) is not None:
+    if hubs.models.User.by_username(value) is not None:
         return value
     raise ValueError('Invalid username')
 
diff --git a/hubs/views/api.py b/hubs/views/api.py
index 18ca0ba..4c96e44 100644
--- a/hubs/views/api.py
+++ b/hubs/views/api.py
@@ -12,8 +12,8 @@ from .utils import get_hub, login_required
 @login_required
 def hub_subscribe(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
-    hub.subscribe(flask.g.db, user)
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
+    hub.subscribe(user)
     flask.g.db.commit()
     return flask.redirect(flask.url_for('hub', name=hub.name))
 
@@ -22,9 +22,9 @@ def hub_subscribe(hub):
 @login_required
 def hub_unsubscribe(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
     try:
-        hub.unsubscribe(flask.g.db, user)
+        hub.unsubscribe(user)
     except KeyError:
         return flask.abort(400)
     flask.g.db.commit()
@@ -35,8 +35,8 @@ def hub_unsubscribe(hub):
 @login_required
 def hub_star(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
-    hub.subscribe(flask.g.db, user, role='stargazer')
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
+    hub.subscribe(user, role='stargazer')
     flask.g.db.commit()
     return flask.redirect(flask.url_for('hub', name=hub.name))
 
@@ -45,9 +45,9 @@ def hub_star(hub):
 @login_required
 def hub_unstar(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
     try:
-        hub.unsubscribe(flask.g.db, user, role='stargazer')
+        hub.unsubscribe(user, role='stargazer')
     except KeyError:
         return flask.abort(400)
     flask.g.db.commit()
@@ -58,8 +58,8 @@ def hub_unstar(hub):
 @login_required
 def hub_join(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
-    hub.subscribe(flask.g.db, user, role='member')
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
+    hub.subscribe(user, role='member')
     flask.g.db.commit()
     return flask.redirect(flask.url_for('hub', name=hub.name))
 
@@ -68,9 +68,9 @@ def hub_join(hub):
 @login_required
 def hub_leave(hub):
     hub = get_hub(hub)
-    user = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
+    user = hubs.models.User.by_username(flask.g.auth.nickname)
     try:
-        hub.unsubscribe(flask.g.db, user, role='member')
+        hub.unsubscribe(user, role='member')
     except KeyError:
         return flask.abort(400)
     flask.g.db.commit()
diff --git a/hubs/views/hub.py b/hubs/views/hub.py
index 12b75e9..f64f261 100644
--- a/hubs/views/hub.py
+++ b/hubs/views/hub.py
@@ -20,7 +20,7 @@ def hub(name):
 @app.route('/<name>/json')
 def hub_json(name):
     hub = get_hub(name)
-    response = flask.jsonify(hub.__json__(flask.g.db))
+    response = flask.jsonify(hub.__json__())
     # TODO -- modify headers with response.headers['X-fedora-hubs-wat'] = 'foo'
     return response
 
diff --git a/hubs/views/plus_plus.py b/hubs/views/plus_plus.py
index 266c2ea..4e25746 100644
--- a/hubs/views/plus_plus.py
+++ b/hubs/views/plus_plus.py
@@ -15,7 +15,7 @@ from .utils import login_required
 
 @app.route('/plus_plus/<user>/status', methods=['GET'])
 def plus_plus_status(user):
-    receiver = hubs.models.User.by_username(flask.g.db, user)
+    receiver = hubs.models.User.by_username(user)
     if not receiver:
         return 'User does not exist', 403
     pp_url = app.config['PLUS_PLUS_URL'] + str(receiver.username)
@@ -43,7 +43,7 @@ def plus_plus_update_bool_helper(val):
 @app.route('/plus_plus/<user>/update', methods=['POST'])
 @login_required
 def plus_plus_update(user):
-    receiver = hubs.models.User.by_username(flask.g.db, user)
+    receiver = hubs.models.User.by_username(user)
 
     if not receiver:
         return 'User does not exist', 403
@@ -60,7 +60,7 @@ def plus_plus_update(user):
 
     update_bool_val = plus_plus_update_bool_helper(flask.request.form[update])
     pp_url = app.config['PLUS_PLUS_URL'] + str(receiver.username)
-    sender = hubs.models.User.by_username(flask.g.db, flask.g.auth.nickname)
+    sender = hubs.models.User.by_username(flask.g.auth.nickname)
     pp_token = app.config['PLUS_PLUS_TOKEN']
     auth_header = {'Authorization': 'token {}'.format(pp_token)}
     data = {'sender': sender.username, update: update_bool_val}
diff --git a/hubs/views/root.py b/hubs/views/root.py
index cc03161..6b9102f 100644
--- a/hubs/views/root.py
+++ b/hubs/views/root.py
@@ -22,12 +22,12 @@ def groups():
 
     # Get the list of promoted and non-promoted group hubs from the DB
     promoted_names = app.config.get('PROMOTED_GROUPS')
-    groups = hubs.models.Hub.all_group_hubs(flask.g.db)
+    groups = hubs.models.Hub.all_group_hubs()
     promoted = [g for g in groups if g.name in promoted_names]
     secondary = [g for g in groups if g.name not in promoted_names]
 
     name_of_the_month = app.config.get('HUB_OF_THE_MONTH')
-    hub_of_the_month = hubs.models.Hub.by_name(flask.g.db, name_of_the_month)
+    hub_of_the_month = hubs.models.Hub.by_name(name_of_the_month)
 
     return flask.render_template(
         'groups.html',
diff --git a/hubs/views/user.py b/hubs/views/user.py
index cab84ed..692daf3 100644
--- a/hubs/views/user.py
+++ b/hubs/views/user.py
@@ -14,7 +14,7 @@ from .utils import login_required, get_hub
 @login_required
 def stream(name):
     hub = get_hub(name)
-    saved = hubs.models.SavedNotification.by_username(flask.g.db, name)
+    saved = hubs.models.SavedNotification.by_username(name)
     saved = [n.__json__() for n in saved]
 
     stream = hubs.stream.Stream()
@@ -33,13 +33,13 @@ def stream(name):
 @login_required
 def notifications(user):
     if flask.request.method == 'GET':
-        notifications = hubs.models.SavedNotification.by_username(flask.g.db, user)
+        notifications = hubs.models.SavedNotification.by_username(user)
         notifications = [n.__json__() for n in notifications]
         return flask.jsonify(notifications)
 
     if flask.request.method == 'POST':
         data = flask.request.get_json()
-        user = hubs.models.User.by_username(flask.g.db, user)
+        user = hubs.models.User.by_username(user)
         if not user:
             return flask.abort(400)
         try:
diff --git a/hubs/views/widget.py b/hubs/views/widget.py
index d40ff3f..f413985 100644
--- a/hubs/views/widget.py
+++ b/hubs/views/widget.py
@@ -11,7 +11,7 @@ from .utils import get_widget
 @app.route('/<hub>/<int:idx>')
 def widget_render(hub, idx):
     widget = get_widget(hub, idx)
-    return widget.render(flask.g.db)  # , edit=False)
+    return widget.render()  # , edit=False)
     # was blocking all widgets from working, sorry!
 
 
@@ -19,7 +19,7 @@ def widget_render(hub, idx):
 @app.route('/<hub>/<int:idx>/json/')
 def widget_json(hub, idx):
     widget = get_widget(hub, idx)
-    response = flask.jsonify(widget.__json__(flask.g.db))
+    response = flask.jsonify(widget.__json__())
     # TODO -- modify headers with response.headers['X-fedora-hubs-wat'] = 'foo'
     return response
 
diff --git a/hubs/widgets/memberships.py b/hubs/widgets/memberships.py
index 2763db0..95beb74 100644
--- a/hubs/widgets/memberships.py
+++ b/hubs/widgets/memberships.py
@@ -17,8 +17,8 @@ def data(session, widget, **kwargs):
     hub = widget.hub
     members = []
     if hub.user_hub:
-        user = hubs.models.User.by_username(session, hub.name)
-        members = [m.__json__(session) for m in user.memberships
+        user = hubs.models.User.by_username(hub.name)
+        members = [m.__json__() for m in user.memberships
                    if m.name != user.username]
     else:
         members_name = []
@@ -26,7 +26,7 @@ def data(session, widget, **kwargs):
             if member.username in members_name:
                 continue
             members_name.append(member.username)
-            members.append(member.__json__(session))
+            members.append(member.__json__())
 
     oldest_members = sorted(members,
                             key=lambda m: m.get('created_on'))[:ELLIPSIS_LIMIT]
diff --git a/populate-from-fas.py b/populate-from-fas.py
index b74e8a6..959c5e4 100755
--- a/populate-from-fas.py
+++ b/populate-from-fas.py
@@ -60,7 +60,7 @@ for letter in reversed(sorted(list(set(string.letters.lower())))):
     session = hubs.models.init(
         fedmsg_config['hubs.sqlalchemy.uri'], True, True)
     for user in users:
-        hubs_user = hubs.models.User.by_username(session, user['username'])
+        hubs_user = hubs.models.User.by_username(user['username'])
 
         # Build a lookup by group id
         roles = dict([(r.group_id, r) for r in user['roles']])
@@ -91,11 +91,11 @@ for letter in reversed(sorted(list(set(string.letters.lower())))):
             )
 
             if hubs_user not in hub.subscribers:
-                hub.subscribe(session, hubs_user, role='subscriber')
+                hub.subscribe(hubs_user, role='subscriber')
             if hubs_user not in hub.members:
-                hub.subscribe(session, hubs_user, role='member')
+                hub.subscribe(hubs_user, role='member')
             if hubs_user not in hub.owners:
                 if role['role_type'] in [u'administrator', u'sponsor']:
-                    hub.subscribe(session, hubs_user, role='owner')
+                    hub.subscribe(hubs_user, role='owner')
 
     session.commit()
diff --git a/populate.py b/populate.py
index 4286940..d4b262d 100755
--- a/populate.py
+++ b/populate.py
@@ -62,9 +62,9 @@ hub.widgets.append(widget)
 
 
 # Set up some memberships
-hub.subscribe(session, hubs.models.User.by_username(session, 'pravins'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'decause'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ralph'), 'subscriber')
+hub.subscribe(hubs.models.User.by_username('pravins'), 'owner')
+hub.subscribe(hubs.models.User.by_username('decause'), 'member')
+hub.subscribe(hubs.models.User.by_username('ralph'), 'subscriber')
 
 
 session.commit()
@@ -107,11 +107,11 @@ hub.widgets.append(widget)
 
 
 # Set up some memberships
-hub.subscribe(session, hubs.models.User.by_username(session, 'decause'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'jflory7'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'bee2502'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'keekri'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'linuxmodder'), 'member')
+hub.subscribe(hubs.models.User.by_username('decause'), 'owner')
+hub.subscribe(hubs.models.User.by_username('jflory7'), 'member')
+hub.subscribe(hubs.models.User.by_username('bee2502'), 'member')
+hub.subscribe(hubs.models.User.by_username('keekri'), 'member')
+hub.subscribe(hubs.models.User.by_username('linuxmodder'), 'member')
 
 
 session.commit()
@@ -154,12 +154,12 @@ hub.widgets.append(widget)
 
 
 # Set up some memberships
-hub.subscribe(session, hubs.models.User.by_username(session, 'croberts'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ryanlerch'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'mrichard'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'mattdm'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'decause'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ralph'), 'subscriber')
+hub.subscribe(hubs.models.User.by_username('croberts'), 'owner')
+hub.subscribe(hubs.models.User.by_username('ryanlerch'), 'owner')
+hub.subscribe(hubs.models.User.by_username('mrichard'), 'member')
+hub.subscribe(hubs.models.User.by_username('mattdm'), 'member')
+hub.subscribe(hubs.models.User.by_username('decause'), 'member')
+hub.subscribe(hubs.models.User.by_username('ralph'), 'subscriber')
 
 
 session.commit()
@@ -202,13 +202,13 @@ hub.widgets.append(widget)
 
 
 # Set up some memberships
-hub.subscribe(session, hubs.models.User.by_username(session, 'duffy'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ryanlerch'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'gnokii'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'mrichard'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'nask0'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'decause'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ralph'), 'subscriber')
+hub.subscribe(hubs.models.User.by_username('duffy'), 'owner')
+hub.subscribe(hubs.models.User.by_username('ryanlerch'), 'owner')
+hub.subscribe(hubs.models.User.by_username('gnokii'), 'owner')
+hub.subscribe(hubs.models.User.by_username('mrichard'), 'owner')
+hub.subscribe(hubs.models.User.by_username('nask0'), 'member')
+hub.subscribe(hubs.models.User.by_username('decause'), 'member')
+hub.subscribe(hubs.models.User.by_username('ralph'), 'subscriber')
 
 session.commit()
 
@@ -251,10 +251,10 @@ hub.widgets.append(widget)
 
 vc = hubs.models.VisitCounter().get_or_create(session, 'ralph', 'mrichard')
 hubs.models.VisitCounter().increment_visits(session, 'ralph', 'mrichard')
-hub.subscribe(session, hubs.models.User.by_username(session, 'ralph'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'abompard'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'lmacken'), 'owner')
-hub.subscribe(session, hubs.models.User.by_username(session, 'nask0'), 'member')
-hub.subscribe(session, hubs.models.User.by_username(session, 'decause'), 'subscriber')
+hub.subscribe(hubs.models.User.by_username('ralph'), 'owner')
+hub.subscribe(hubs.models.User.by_username('abompard'), 'owner')
+hub.subscribe(hubs.models.User.by_username('lmacken'), 'owner')
+hub.subscribe(hubs.models.User.by_username('nask0'), 'member')
+hub.subscribe(hubs.models.User.by_username('decause'), 'subscriber')
 
 session.commit()

