Commits

Marcin Kuzminski committed 04027bd

Refactoring of model get functions

Comments (0)

Files changed (16)

rhodecode/controllers/admin/permissions.py

         c.create_choices = self.create_choices
 
         if id == 'default':
-            default_user = User.by_username('default')
+            default_user = User.get_by_username('default')
             defaults = {'_method': 'put',
                         'anonymous': default_user.active}
 

rhodecode/controllers/admin/repos.py

         """
         self.__load_defaults()
 
-        c.repo_info = db_repo = Repository.by_repo_name(repo_name)
+        c.repo_info = db_repo = Repository.get_by_repo_name(repo_name)
         repo = scm_repo = db_repo.scm_instance
 
         if c.repo_info is None:
 
             return redirect(url('repos'))
 
-        c.default_user_id = User.by_username('default').user_id
+        c.default_user_id = User.get_by_username('default').user_id
         c.in_public_journal = self.sa.query(UserFollowing)\
             .filter(UserFollowing.user_id == c.default_user_id)\
             .filter(UserFollowing.follows_repository == c.repo_info).scalar()
         token = get_token()
         if cur_token == token:
             try:
-                repo_id = Repository.by_repo_name(repo_name).repo_id
-                user_id = User.by_username('default').user_id
+                repo_id = Repository.get_by_repo_name(repo_name).repo_id
+                user_id = User.get_by_username('default').user_id
                 self.scm_model.toggle_following_repo(repo_id, user_id)
                 h.flash(_('Updated repository visibility in public journal'),
                         category='success')

rhodecode/controllers/login.py

                 c.form_result = login_form.to_python(dict(request.POST))
                 #form checks for username/password, now we're authenticated
                 username = c.form_result['username']
-                user = User.by_username(username,
-                                                   case_insensitive=True)
+                user = User.get_by_username(username, case_insensitive=True)
                 auth_user = AuthUser(user.user_id)
                 auth_user.set_authenticated()
                 session['rhodecode_user'] = auth_user
     def register(self):
         user_model = UserModel()
         c.auto_active = False
-        for perm in user_model.get_by_username('default',
-                                               cache=False).user_perms:
+        for perm in User.get_by_username('default').user_perms:
             if perm.permission.permission_name == 'hg.register.auto_activate':
                 c.auto_active = True
                 break

rhodecode/lib/auth.py

 
 from rhodecode.model import meta
 from rhodecode.model.user import UserModel
-from rhodecode.model.db import Permission, RhodeCodeSettings
+from rhodecode.model.db import Permission, RhodeCodeSettings, User
 
 log = logging.getLogger(__name__)
 
     """
 
     user_model = UserModel()
-    user = user_model.get_by_username(username, cache=False)
+    user = User.get_by_username(username)
 
     log.debug('Authenticating user using RhodeCode account')
     if user is not None and not user.ldap_dn:
 
     else:
         log.debug('Regular authentication failed')
-        user_obj = user_model.get_by_username(username, cache=False,
-                                            case_insensitive=True)
+        user_obj = User.get_by_username(username, case_insensitive=True)
 
         if user_obj is not None and not user_obj.ldap_dn:
             log.debug('this user already exists as non ldap')
 
     def propagate_data(self):
         user_model = UserModel()
-        self.anonymous_user = user_model.get_by_username('default', cache=True)
+        self.anonymous_user = User.get_by_username('default')
         if self._api_key and self._api_key != self.anonymous_user.api_key:
             #try go get user by api key
             log.debug('Auth User lookup by API KEY %s', self._api_key)

rhodecode/lib/base.py

         super(BaseRepoController, self).__before__()
         if c.repo_name:
 
-            c.rhodecode_db_repo = Repository.by_repo_name(c.repo_name)
+            c.rhodecode_db_repo = Repository.get_by_repo_name(c.repo_name)
             c.rhodecode_repo = c.rhodecode_db_repo.scm_instance
 
             if c.rhodecode_repo is None:

rhodecode/lib/middleware/simplegit.py

         return repo_name
 
     def __get_user(self, username):
-        return User.by_username(username)
+        return User.get_by_username(username)
 
     def __get_action(self, environ):
         """Maps git request commands into a pull or push command.

rhodecode/lib/middleware/simplehg.py

         return repo_name
 
     def __get_user(self, username):
-        return User.by_username(username)
+        return User.get_by_username(username)
 
     def __get_action(self, environ):
         """

rhodecode/lib/utils.py

         if hasattr(user, 'user_id'):
             user_obj = user
         elif isinstance(user, basestring):
-            user_obj = User.by_username(user)
+            user_obj = User.get_by_username(user)
         else:
             raise Exception('You have to provide user object or username')
 

rhodecode/model/db.py

             return self.__class__.__name__
 
     @classmethod
-    def by_username(cls, username, case_insensitive=False):
+    def get_by_username(cls, username, case_insensitive=False):
         if case_insensitive:
-            return Session.query(cls).filter(cls.username.like(username)).one()
+            return Session.query(cls).filter(cls.username.like(username)).scalar()
         else:
-            return Session.query(cls).filter(cls.username == username).one()
+            return Session.query(cls).filter(cls.username == username).scalar()
 
     @classmethod
     def get_by_api_key(cls, api_key):
         return Session.query(cls).filter(cls.api_key == api_key).one()
 
-
     def update_lastlogin(self):
         """Update user lastlogin"""
 
                                   self.repo_id, self.repo_name)
 
     @classmethod
-    def by_repo_name(cls, repo_name):
+    def get_by_repo_name(cls, repo_name):
         q = Session.query(cls).filter(cls.repo_name == repo_name)
 
         q = q.options(joinedload(Repository.fork))\

rhodecode/model/forms.py

                 old_un = UserModel().get(old_data.get('user_id')).username
 
             if old_un != value or not edit:
-                if UserModel().get_by_username(value, cache=False,
-                                               case_insensitive=True):
+                if User.get_by_username(value, case_insensitive=True):
                     raise formencode.Invalid(_('This username already '
                                                'exists') , value, state)
 
     def validate_python(self, value, state):
         password = value['password']
         username = value['username']
-        user = UserModel().get_by_username(username)
+        user = User.get_by_username(username)
 
         if authenticate(username, password):
             return value

rhodecode/model/repo.py

             for member, perm, member_type in form_data['perms_updates']:
                 if member_type == 'user':
                     r2p = self.sa.query(RepoToPerm)\
-                            .filter(RepoToPerm.user == User.by_username(member))\
+                            .filter(RepoToPerm.user == User.get_by_username(member))\
                             .filter(RepoToPerm.repository == cur_repo)\
                             .one()
 
                 if member_type == 'user':
                     r2p = RepoToPerm()
                     r2p.repository = cur_repo
-                    r2p.user = User.by_username(member)
+                    r2p.user = User.get_by_username(member)
 
                     r2p.permission = self.sa.query(Permission)\
                                         .filter(Permission.
             #update current repo
             for k, v in form_data.items():
                 if k == 'user':
-                    cur_repo.user = User.by_username(v)
+                    cur_repo.user = User.get_by_username(v)
                 elif k == 'repo_name':
                     cur_repo.repo_name = form_data['repo_name_full']
                 elif k == 'repo_group':
             #create default permission
             repo_to_perm = RepoToPerm()
             default = 'repository.read'
-            for p in UserModel(self.sa).get_by_username('default',
-                                                    cache=False).user_perms:
+            for p in User.get_by_username('default').user_perms:
                 if p.permission.permission_name.startswith('repository.'):
                     default = p.permission.permission_name
                     break
                     .one().permission_id
 
             repo_to_perm.repository = new_repo
-            repo_to_perm.user_id = UserModel(self.sa)\
-                .get_by_username('default', cache=False).user_id
+            repo_to_perm.user_id = User.get_by_username('default').user_id
 
             self.sa.add(repo_to_perm)
 

rhodecode/model/scm.py

 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
-import os
 import time
 import traceback
 import logging
 from rhodecode.lib.utils import get_repos as get_filesystem_repos, make_ui, \
     action_logger, EmptyChangeset
 from rhodecode.model import BaseModel
-from rhodecode.model.user import UserModel
 from rhodecode.model.db import Repository, RhodeCodeUi, CacheInvalidation, \
-    UserFollowing, UserLog
+    UserFollowing, UserLog, User
 
 log = logging.getLogger(__name__)
 
         return f is not None
 
     def is_following_user(self, username, user_id, cache=False):
-        u = UserModel(self.sa).get_by_username(username)
+        u = User.get_by_username(username)
 
         f = self.sa.query(UserFollowing)\
             .filter(UserFollowing.follows_user == u)\
 
     def get_followers(self, repo_id):
         if not isinstance(repo_id, int):
-            repo_id = getattr(Repository.by_repo_name(repo_id), 'repo_id')
+            repo_id = getattr(Repository.get_by_repo_name(repo_id), 'repo_id')
 
         return self.sa.query(UserFollowing)\
                 .filter(UserFollowing.follows_repo_id == repo_id).count()
 
     def get_forks(self, repo_id):
         if not isinstance(repo_id, int):
-            repo_id = getattr(Repository.by_repo_name(repo_id), 'repo_id')
+            repo_id = getattr(Repository.get_by_repo_name(repo_id), 'repo_id')
 
         return self.sa.query(Repository)\
                 .filter(Repository.fork_id == repo_id).count()
 
     def pull_changes(self, repo_name, username):
-        dbrepo = Repository.by_repo_name(repo_name)
+        dbrepo = Repository.get_by_repo_name(repo_name)
         clone_uri = dbrepo.clone_uri
         if not clone_uri:
             raise Exception("This repository doesn't have a clone uri")
-        
+
         repo = dbrepo.scm_instance
         try:
             extras = {'ip': '',
             from vcs.backends.git import GitInMemoryChangeset as IMC
         # decoding here will force that we have proper encoded values
         # in any other case this will throw exceptions and deny commit
-        
-        if isinstance(content,(basestring,)):
+
+        if isinstance(content, (basestring,)):
             content = safe_str(content)
-        elif isinstance(content,file):
+        elif isinstance(content, file):
             content = content.read()
-            
+
         message = safe_str(message)
         path = safe_str(f_path)
         author = safe_str(author)

rhodecode/tests/functional/test_login.py

 
         # GOOD KEY
 
-        key = User.by_username(username).api_key
+        key = User.get_by_username(username).api_key
 
         response = self.app.get(url(controller='login',
                                     action='password_reset_confirmation',

rhodecode/tests/functional/test_summary.py

 
 
     def _enable_stats(self):
-        r = Repository.by_repo_name(HG_REPO)
+        r = Repository.get_by_repo_name(HG_REPO)
         r.enable_statistics = True
         self.sa.add(r)
         self.sa.commit()

rhodecode/tests/test_hg_operations.py

 USER = 'test_admin'
 PASS = 'test12'
 HOST = '127.0.0.1:5000'
-DEBUG = bool(int(sys.argv[1]))
+DEBUG = True if sys.argv[1:] else False
 print 'DEBUG:', DEBUG
 log = logging.getLogger(__name__)
 
 def test_wrapp(func):
 
     def __wrapp(*args, **kwargs):
-        print '###%s###' % func.__name__
+        print '>>>%s' % func.__name__
         try:
             res = func(*args, **kwargs)
         except Exception, e:
 #smtp_password = 
 #smtp_port = 
 #smtp_use_tls = false
+#smtp_use_ssl = true
 
 [server:main]
 ##nr of threads to spawn
 cut_off_limit = 256000
 force_https = false
 commit_parse_limit = 25
+use_gravatar = true
 
 ####################################
 ###        CELERY CONFIG        ####
 beaker.cache.long_term.type=memory
 beaker.cache.long_term.expire=36000
 
-
 beaker.cache.sql_cache_short.type=memory
 beaker.cache.sql_cache_short.expire=10
 
 ### LOGGING CONFIGURATION   ####
 ################################
 [loggers]
-keys = root, routes, rhodecode, sqlalchemy,beaker,templates
+keys = root, routes, rhodecode, sqlalchemy, beaker, templates
 
 [handlers]
 keys = console
 
 [formatters]
-keys = generic,color_formatter
+keys = generic, color_formatter
 
 #############
 ## LOGGERS ##
 
 [logger_routes]
 level = ERROR
-handlers = console
+handlers = 
 qualname = routes.middleware
 # "level = DEBUG" logs the route matched and routing variables.
+propagate = 1
 
 [logger_beaker]
 level = DEBUG
 
 [logger_rhodecode]
 level = ERROR
-handlers = console
+handlers = 
 qualname = rhodecode
-propagate = 0
+propagate = 1
 
 [logger_sqlalchemy]
 level = ERROR
 class = StreamHandler
 args = (sys.stderr,)
 level = NOTSET
-formatter = color_formatter
+formatter = generic
 
 ################
 ## FORMATTERS ##
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.