Changeset - d75d9ce1320d
[Not reviewed]
default
0 20 1
Thomas De Schampheleire - 9 years ago 2016-09-25 15:06:34
thomas.de.schampheleire@gmail.com
model: move code from __init__.py to base.py

Having too much code, in particular too much imports, inside a package's
__init__.py is a recipe for circular imports, and considered bad practice in
Python [1]

Move out everything from kallithea/model/__init__.py to a new file
kallithea/model/base.py and adapt the existing imports.

[1] http://docs.python-guide.org/en/latest/writing/structure/#packages
21 files changed with 21 insertions and 104 deletions:
0 comments (0 inline, 0 general)
kallithea/config/environment.py
Show inline comments
 
@@ -26,25 +26,25 @@ import beaker
 
import formencode
 

	
 
import kallithea.lib.app_globals as app_globals
 

	
 
from kallithea.config.routing import make_map
 

	
 
from kallithea.lib import helpers
 
from kallithea.lib.auth import set_available_permissions
 
from kallithea.lib.utils import repo2db_mapper, make_ui, set_app_settings, \
 
    load_rcextensions, check_git_version, set_vcs_config, set_indexer_config
 
from kallithea.lib.utils2 import engine_from_config, str2bool
 
from kallithea.lib.db_manage import DbManage
 
from kallithea.model import init_model
 
from kallithea.model.base import init_model
 
from kallithea.model.scm import ScmModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def load_environment(global_conf, app_conf,
 
                     test_env=None, test_index=None):
 
    """
 
    Configure the Pylons environment via the ``pylons.config``
 
    object
 
    """
 
    config = pylons.configuration.PylonsConfig()
kallithea/lib/celerylib/__init__.py
Show inline comments
 
@@ -28,25 +28,25 @@ Original author and date, and relevant c
 

	
 
import os
 
import logging
 

	
 
from pylons import config
 

	
 
from hashlib import md5
 
from decorator import decorator
 

	
 
from kallithea import CELERY_ON, CELERY_EAGER
 
from kallithea.lib.utils2 import safe_str
 
from kallithea.lib.pidlock import DaemonLock, LockHeld
 
from kallithea.model import init_model
 
from kallithea.model.base import init_model
 
from kallithea.model import meta
 

	
 
from sqlalchemy import engine_from_config
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class FakeTask(object):
 
    """Fake a sync result to make it look like a finished task"""
 

	
 
    def __init__(self, result):
kallithea/lib/db_manage.py
Show inline comments
 
@@ -29,25 +29,25 @@ Original author and date, and relevant c
 
import os
 
import sys
 
import time
 
import uuid
 
import logging
 
from os.path import dirname
 

	
 
import alembic.config
 
import alembic.command
 

	
 
from kallithea.lib.paster_commands.common import ask_ok
 
from kallithea.model.user import UserModel
 
from kallithea.model import init_model
 
from kallithea.model.base import init_model
 
from kallithea.model.db import User, Permission, Ui, \
 
    Setting, UserToPerm, RepoGroup, \
 
    UserRepoGroupToPerm, CacheInvalidation, Repository
 

	
 
from sqlalchemy.engine import create_engine
 
from kallithea.model.repo_group import RepoGroupModel
 
#from kallithea.model import meta
 
from kallithea.model.meta import Session, Base
 
from kallithea.model.repo import RepoModel
 
from kallithea.model.permission import PermissionModel
 

	
 

	
kallithea/lib/hooks.py
Show inline comments
 
@@ -375,25 +375,25 @@ def handle_git_receive(repo_path, revs, 
 
    A really hacky method that is run by git post-receive hook and logs
 
    a push action together with pushed revisions. It's executed by subprocess
 
    thus needs all info to be able to create an on the fly app environment,
 
    connect to database and run the logging code. Hacky as sh*t but works.
 

	
 
    :param repo_path:
 
    :param revs:
 
    :param env:
 
    """
 
    from paste.deploy import appconfig
 
    from sqlalchemy import engine_from_config
 
    from kallithea.config.environment import load_environment
 
    from kallithea.model import init_model
 
    from kallithea.model.base import init_model
 
    from kallithea.model.db import Ui
 
    from kallithea.lib.utils import make_ui
 
    extras = _extract_extras(env)
 

	
 
    repo_path = safe_unicode(repo_path)
 
    path, ini_name = os.path.split(extras['config'])
 
    conf = appconfig('config:%s' % ini_name, relative_to=path)
 
    load_environment(conf.global_conf, conf.local_conf, test_env=False,
 
                     test_index=False)
 

	
 
    engine = engine_from_config(conf, 'sqlalchemy.')
 
    init_model(engine)
kallithea/lib/paster_commands/common.py
Show inline comments
 
@@ -91,17 +91,17 @@ class BasePasterCommand(Command):
 

	
 
        self.path_to_ini_file = os.path.realpath(conf)
 
        conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
 
        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
 

	
 
    def _init_session(self):
 
        """
 
        Inits SqlAlchemy Session
 
        """
 
        logging.config.fileConfig(self.path_to_ini_file)
 

	
 
        from pylons import config
 
        from kallithea.model import init_model
 
        from kallithea.model.base import init_model
 
        from kallithea.lib.utils2 import engine_from_config
 
        setup_cache_regions(config)
 
        engine = engine_from_config(config, 'sqlalchemy.')
 
        init_model(engine)
kallithea/model/__init__.py
Show inline comments
 
@@ -14,96 +14,13 @@
 
"""
 
kallithea.model
 
~~~~~~~~~~~~~~~
 

	
 
The application's model objects
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Nov 25, 2010
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 

	
 

	
 
:example:
 

	
 
    .. code-block:: python
 

	
 
       from paste.deploy import appconfig
 
       from pylons import config
 
       from sqlalchemy import engine_from_config
 
       from kallithea.config.environment import load_environment
 

	
 
       conf = appconfig('config:development.ini', relative_to = './../../')
 
       load_environment(conf.global_conf, conf.local_conf)
 

	
 
       engine = engine_from_config(config, 'sqlalchemy.')
 
       init_model(engine)
 
       # RUN YOUR CODE HERE
 

	
 
"""
 

	
 

	
 
import logging
 
from kallithea.model import meta
 
from kallithea.lib.utils2 import obfuscate_url_pw
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def init_model(engine):
 
    """
 
    Initializes db session, bind the engine with the metadata,
 
    Call this before using any of the tables or classes in the model,
 
    preferably once in application start
 

	
 
    :param engine: engine to bind to
 
    """
 
    engine_str = obfuscate_url_pw(str(engine.url))
 
    log.info("initializing db for %s", engine_str)
 
    meta.Base.metadata.bind = engine
 

	
 

	
 
class BaseModel(object):
 
    """
 
    Base Model for all Kallithea models, it adds sql alchemy session
 
    into instance of model
 

	
 
    :param sa: If passed it reuses this session instead of creating a new one
 
    """
 

	
 
    def __init__(self, sa=None):
 
        if sa is not None:
 
            self.sa = sa
 
        else:
 
            self.sa = meta.Session()
 

	
 
    def _get_user(self, user):
 
        """
 
        Helper method to get user by ID, or username fallback
 

	
 
        :param user: UserID, username, or User instance
 
        """
 
        from kallithea.model.db import User
 
        return User.guess_instance(user,
 
                                  callback=User.get_by_username)
 

	
 
    def _get_repo(self, repository):
 
        """
 
        Helper method to get repository by ID, or repository name
 

	
 
        :param repository: RepoID, repository name or Repository Instance
 
        """
 
        from kallithea.model.db import Repository
 
        return Repository.guess_instance(repository,
 
                                  callback=Repository.get_by_repo_name)
 

	
 
    def _get_perm(self, permission):
 
        """
 
        Helper method to get permission by ID, or permission name
 

	
 
        :param permission: PermissionID, permission_name or Permission instance
 
        """
 
        from kallithea.model.db import Permission
 
        return Permission.guess_instance(permission,
 
                                  callback=Permission.get_by_key)
kallithea/model/api_key.py
Show inline comments
 
@@ -21,25 +21,25 @@ This file was forked by the Kallithea pr
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Sep 8, 2013
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import time
 
import logging
 
from sqlalchemy import or_
 

	
 
from kallithea.lib.utils2 import generate_api_key
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import UserApiKeys
 
from kallithea.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ApiKeyModel(BaseModel):
 

	
 
    def create(self, user, description, lifetime=-1):
 
        """
 
        :param user: user or user_id
 
        :param description: description of ApiKey
kallithea/model/base.py
Show inline comments
 
file copied from kallithea/model/__init__.py to kallithea/model/base.py
 
@@ -3,26 +3,26 @@
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
"""
 
kallithea.model
 
~~~~~~~~~~~~~~~
 
kallithea.model.base
 
~~~~~~~~~~~~~~~~~~~~
 

	
 
The application's model objects
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Nov 25, 2010
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 

	
 

	
 
:example:
kallithea/model/changeset_status.py
Show inline comments
 
@@ -19,25 +19,25 @@ Changeset status controller
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Apr 30, 2012
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import logging
 
from sqlalchemy.orm import joinedload
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import ChangesetStatus, PullRequest
 
from kallithea.lib.exceptions import StatusChangeOnClosedPullRequestError
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetStatusModel(BaseModel):
 

	
 
    def _get_status_query(self, repo, revision, pull_request,
 
                          with_revisions=False):
 
        repo = self._get_repo(repo)
 

	
kallithea/model/comment.py
Show inline comments
 
@@ -23,25 +23,25 @@ Original author and date, and relevant c
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import logging
 

	
 
from pylons.i18n.translation import _
 
from collections import defaultdict
 

	
 
from kallithea.lib.utils2 import extract_mentioned_users, safe_unicode
 
from kallithea.lib import helpers as h
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import ChangesetComment, User, \
 
    Notification, PullRequest
 
from kallithea.model.notification import NotificationModel
 
from kallithea.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetCommentsModel(BaseModel):
 

	
 
    def _get_notification_data(self, repo, comment, author, comment_text,
 
                               line_no=None, revision=None, pull_request=None,
kallithea/model/gist.py
Show inline comments
 
@@ -25,25 +25,25 @@ Original author and date, and relevant c
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import os
 
import time
 
import logging
 
import traceback
 
import shutil
 

	
 
from kallithea.lib.utils2 import safe_unicode, unique_id, safe_int, \
 
    time_to_datetime, AttributeDict
 
from kallithea.lib.compat import json
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import Gist
 
from kallithea.model.repo import RepoModel
 
from kallithea.model.scm import ScmModel
 

	
 
log = logging.getLogger(__name__)
 

	
 
GIST_STORE_LOC = '.rc_gist_store'
 
GIST_METADATA_FILE = '.rc_gist_metadata'
 

	
 

	
 
class GistModel(BaseModel):
 

	
kallithea/model/notification.py
Show inline comments
 
@@ -27,25 +27,25 @@ Original author and date, and relevant c
 
"""
 

	
 
import logging
 
import traceback
 

	
 
from pylons import tmpl_context as c
 
from pylons.i18n.translation import _
 
from sqlalchemy.orm import joinedload, subqueryload
 

	
 
import kallithea
 
from kallithea.lib import helpers as h
 
from kallithea.lib.utils2 import safe_unicode
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import Notification, User, UserNotification
 
from kallithea.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class NotificationModel(BaseModel):
 

	
 
    def create(self, created_by, subject, body, recipients=None,
 
               type_=Notification.TYPE_MESSAGE, with_email=True,
 
               email_kwargs=None, repo_name=None):
 
        """
kallithea/model/permission.py
Show inline comments
 
@@ -22,25 +22,25 @@ Original author and date, and relevant c
 
:created_on: Aug 20, 2010
 
:author: marcink
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 

	
 
import logging
 
import traceback
 

	
 
from sqlalchemy.exc import DatabaseError
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import User, Permission, UserToPerm, UserRepoToPerm, \
 
    UserRepoGroupToPerm, UserUserGroupToPerm
 
from kallithea.lib.utils2 import str2bool
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PermissionModel(BaseModel):
 
    """
 
    Permissions model for Kallithea
 
    """
 

	
kallithea/model/pull_request.py
Show inline comments
 
@@ -26,25 +26,25 @@ Original author and date, and relevant c
 
"""
 

	
 
import logging
 
import datetime
 

	
 
from pylons.i18n.translation import _
 

	
 
from sqlalchemy.orm import joinedload
 

	
 
from kallithea.model.meta import Session
 
from kallithea.lib import helpers as h
 
from kallithea.lib.exceptions import UserInvalidException
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import PullRequest, PullRequestReviewers, Notification, \
 
    ChangesetStatus, User
 
from kallithea.model.notification import NotificationModel
 
from kallithea.lib.utils2 import extract_mentioned_users, safe_unicode
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PullRequestModel(BaseModel):
 

	
 
    def _get_valid_reviewers(self, seq):
kallithea/model/repo.py
Show inline comments
 
@@ -32,25 +32,25 @@ import logging
 
import traceback
 
from datetime import datetime
 
from sqlalchemy.orm import subqueryload
 

	
 
from kallithea.lib.utils import make_ui
 
from kallithea.lib.vcs.backends import get_backend
 
from kallithea.lib.compat import json
 
from kallithea.lib.utils2 import LazyProperty, safe_str, safe_unicode, \
 
    remove_prefix, obfuscate_url_pw, get_current_authuser
 
from kallithea.lib.caching_query import FromCache
 
from kallithea.lib.hooks import log_delete_repository
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import Repository, UserRepoToPerm, UserGroupRepoToPerm, \
 
    UserRepoGroupToPerm, UserGroupRepoGroupToPerm, User, Permission, \
 
    Statistics, UserGroup, Ui, RepoGroup, RepositoryField
 

	
 
from kallithea.lib import helpers as h
 
from kallithea.lib.auth import HasRepoPermissionAny, HasUserGroupPermissionAny
 
from kallithea.lib.exceptions import AttachedForksError
 
from kallithea.model.scm import UserGroupList
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
kallithea/model/repo_group.py
Show inline comments
 
@@ -25,25 +25,25 @@ Original author and date, and relevant c
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 

	
 
import os
 
import logging
 
import traceback
 
import shutil
 
import datetime
 

	
 
from kallithea.lib.utils2 import LazyProperty
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import RepoGroup, Ui, UserRepoGroupToPerm, \
 
    User, Permission, UserGroupRepoGroupToPerm, UserGroup, Repository
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepoGroupModel(BaseModel):
 

	
 
    def _get_user_group(self, users_group):
 
        return UserGroup.guess_instance(users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
kallithea/model/repo_permission.py
Show inline comments
 
@@ -15,25 +15,25 @@
 
kallithea.model.repo_permission
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
repository permission model for Kallithea
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Oct 1, 2011
 
:author: nvinot, marcink
 
"""
 

	
 
import logging
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import UserRepoToPerm, UserGroupRepoToPerm, \
 
    Permission
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepositoryPermissionModel(BaseModel):
 

	
 
    def get_user_permission(self, repository, user):
 
        repository = self._get_repo(repository)
 
        user = self._get_user(user)
 

	
kallithea/model/scm.py
Show inline comments
 
@@ -44,25 +44,25 @@ from kallithea.lib.vcs.exceptions import
 
from kallithea.lib.vcs.utils.lazy import LazyProperty
 
from kallithea.lib.vcs.nodes import FileNode
 
from kallithea.lib.vcs.backends.base import EmptyChangeset
 

	
 
from kallithea import BACKENDS
 
from kallithea.lib import helpers as h
 
from kallithea.lib.utils2 import safe_str, safe_unicode, get_server_url, \
 
    _set_extras
 
from kallithea.lib.auth import HasRepoPermissionAny, HasRepoGroupPermissionAny, \
 
    HasUserGroupPermissionAny, HasPermissionAny, HasPermissionAny
 
from kallithea.lib.utils import get_filesystem_repos, make_ui, \
 
    action_logger
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import Repository, Ui, CacheInvalidation, \
 
    UserFollowing, UserLog, User, RepoGroup, PullRequest
 
from kallithea.lib.hooks import log_push_action
 
from kallithea.lib.exceptions import NonRelativePathError, IMCCommitError
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserTemp(object):
 
    def __init__(self, user_id):
 
        self.user_id = user_id
 

	
kallithea/model/user.py
Show inline comments
 
@@ -30,25 +30,25 @@ import hashlib
 
import hmac
 
import logging
 
import time
 
import traceback
 

	
 
from pylons import config
 
from pylons.i18n.translation import _
 

	
 
from sqlalchemy.exc import DatabaseError
 

	
 
from kallithea.lib.utils2 import safe_str, generate_api_key, get_current_authuser
 
from kallithea.lib.caching_query import FromCache
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import User, UserToPerm, Notification, \
 
    UserEmailMap, UserIpMap
 
from kallithea.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from kallithea.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserModel(BaseModel):
 
    password_reset_token_lifetime = 86400 # 24 hours
kallithea/model/user_group.py
Show inline comments
 
@@ -18,25 +18,25 @@ kallithea.model.user_group
 
user group model for Kallithea
 

	
 
This file was forked by the Kallithea project in July 2014.
 
Original author and date, and relevant copyright and licensing information is below:
 
:created_on: Oct 1, 2011
 
:author: nvinot, marcink
 
"""
 

	
 

	
 
import logging
 
import traceback
 

	
 
from kallithea.model import BaseModel
 
from kallithea.model.base import BaseModel
 
from kallithea.model.db import UserGroupMember, UserGroup, \
 
    UserGroupRepoToPerm, Permission, UserGroupToPerm, User, UserUserGroupToPerm, \
 
    UserGroupUserGroupToPerm
 
from kallithea.lib.exceptions import UserGroupsAssignedException, \
 
    RepoGroupAssignmentError
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserGroupModel(BaseModel):
 

	
 
    def _get_user_group(self, user_group):
kallithea/tests/scripts/manual_test_concurrency.py
Show inline comments
 
@@ -30,25 +30,25 @@ import os
 
import sys
 
import shutil
 
import logging
 
from os.path import dirname
 

	
 
from tempfile import _RandomNameSequence
 
from subprocess import Popen, PIPE
 

	
 
from paste.deploy import appconfig
 
from sqlalchemy import engine_from_config
 

	
 
from kallithea.lib.utils import setup_cache_regions
 
from kallithea.model import init_model
 
from kallithea.model.base import init_model
 
from kallithea.model import meta
 
from kallithea.model.db import User, Repository, Ui
 
from kallithea.lib.auth import get_crypt_password
 

	
 
from kallithea.tests.base import HG_REPO
 
from kallithea.config.environment import load_environment
 

	
 
rel_path = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
 
conf = appconfig('config:development.ini', relative_to=rel_path)
 
load_environment(conf.global_conf, conf.local_conf)
 

	
 
setup_cache_regions(conf)
0 comments (0 inline, 0 general)