##// END OF EJS Templates
db: ported init_model to pyramid.
marcink -
r2342:8478dd31 default
parent child Browse files
Show More
@@ -1,154 +1,155 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 The application's model objects
22 The application's model objects
23
23
24 :example:
24 :example:
25
25
26 .. code-block:: python
26 .. code-block:: python
27
27
28 from paste.deploy import appconfig
28 from paste.deploy import appconfig
29 from pylons import config
29 from pylons import config
30 from sqlalchemy import engine_from_config
30 from sqlalchemy import engine_from_config
31 from rhodecode.config.environment import load_environment
31 from rhodecode.config.environment import load_environment
32
32
33 conf = appconfig('config:development.ini', relative_to = './../../')
33 conf = appconfig('config:development.ini', relative_to = './../../')
34 load_environment(conf.global_conf, conf.local_conf)
34 load_environment(conf.global_conf, conf.local_conf)
35
35
36 engine = engine_from_config(config, 'sqlalchemy.')
36 engine = engine_from_config(config, 'sqlalchemy.')
37 init_model(engine)
37 init_model(engine)
38 # RUN YOUR CODE HERE
38 # RUN YOUR CODE HERE
39
39
40 """
40 """
41
41
42
42
43 import logging
43 import logging
44
44
45 from rhodecode.model import meta, db
45 from rhodecode.model import meta, db
46 from rhodecode.lib.utils2 import obfuscate_url_pw, get_encryption_key
46 from rhodecode.lib.utils2 import obfuscate_url_pw, get_encryption_key
47
47
48 log = logging.getLogger(__name__)
48 log = logging.getLogger(__name__)
49
49
50
50
51 def init_model(engine, encryption_key=None):
51 def init_model(engine, encryption_key=None):
52 """
52 """
53 Initializes db session, bind the engine with the metadata,
53 Initializes db session, bind the engine with the metadata,
54 Call this before using any of the tables or classes in the model,
54 Call this before using any of the tables or classes in the model,
55 preferably once in application start
55 preferably once in application start
56
56
57 :param engine: engine to bind to
57 :param engine: engine to bind to
58 """
58 """
59 engine_str = obfuscate_url_pw(str(engine.url))
59 engine_str = obfuscate_url_pw(str(engine.url))
60 log.info("initializing db for %s", engine_str)
60 log.info("initializing db for %s", engine_str)
61 meta.Base.metadata.bind = engine
61 meta.Base.metadata.bind = engine
62 db.ENCRYPTION_KEY = encryption_key
62 db.ENCRYPTION_KEY = encryption_key
63
63
64
64
65 def init_model_encryption(migration_models):
65 def init_model_encryption(migration_models, config=None):
66 from pylons import config
66 from pyramid.threadlocal import get_current_registry
67 config = config or get_current_registry().settings
67 migration_models.ENCRYPTION_KEY = get_encryption_key(config)
68 migration_models.ENCRYPTION_KEY = get_encryption_key(config)
68 db.ENCRYPTION_KEY = get_encryption_key(config)
69 db.ENCRYPTION_KEY = get_encryption_key(config)
69
70
70
71
71 class BaseModel(object):
72 class BaseModel(object):
72 """
73 """
73 Base Model for all RhodeCode models, it adds sql alchemy session
74 Base Model for all RhodeCode models, it adds sql alchemy session
74 into instance of model
75 into instance of model
75
76
76 :param sa: If passed it reuses this session instead of creating a new one
77 :param sa: If passed it reuses this session instead of creating a new one
77 """
78 """
78
79
79 cls = None # override in child class
80 cls = None # override in child class
80
81
81 def __init__(self, sa=None):
82 def __init__(self, sa=None):
82 if sa is not None:
83 if sa is not None:
83 self.sa = sa
84 self.sa = sa
84 else:
85 else:
85 self.sa = meta.Session()
86 self.sa = meta.Session()
86
87
87 def _get_instance(self, cls, instance, callback=None):
88 def _get_instance(self, cls, instance, callback=None):
88 """
89 """
89 Gets instance of given cls using some simple lookup mechanism.
90 Gets instance of given cls using some simple lookup mechanism.
90
91
91 :param cls: classes to fetch
92 :param cls: classes to fetch
92 :param instance: int or Instance
93 :param instance: int or Instance
93 :param callback: callback to call if all lookups failed
94 :param callback: callback to call if all lookups failed
94 """
95 """
95
96
96 if isinstance(instance, cls):
97 if isinstance(instance, cls):
97 return instance
98 return instance
98 elif isinstance(instance, (int, long)):
99 elif isinstance(instance, (int, long)):
99 if isinstance(cls, tuple):
100 if isinstance(cls, tuple):
100 # if we pass multi instances we pick first to .get()
101 # if we pass multi instances we pick first to .get()
101 cls = cls[0]
102 cls = cls[0]
102 return cls.get(instance)
103 return cls.get(instance)
103 else:
104 else:
104 if instance:
105 if instance:
105 if callback is None:
106 if callback is None:
106 raise Exception(
107 raise Exception(
107 'given object must be int, long or Instance of %s '
108 'given object must be int, long or Instance of %s '
108 'got %s, no callback provided' % (cls, type(instance))
109 'got %s, no callback provided' % (cls, type(instance))
109 )
110 )
110 else:
111 else:
111 return callback(instance)
112 return callback(instance)
112
113
113 def _get_user(self, user):
114 def _get_user(self, user):
114 """
115 """
115 Helper method to get user by ID, or username fallback
116 Helper method to get user by ID, or username fallback
116
117
117 :param user: UserID, username, or User instance
118 :param user: UserID, username, or User instance
118 """
119 """
119 return self._get_instance(
120 return self._get_instance(
120 db.User, user, callback=db.User.get_by_username)
121 db.User, user, callback=db.User.get_by_username)
121
122
122 def _get_user_group(self, user_group):
123 def _get_user_group(self, user_group):
123 """
124 """
124 Helper method to get user by ID, or username fallback
125 Helper method to get user by ID, or username fallback
125
126
126 :param user_group: UserGroupID, user_group_name, or UserGroup instance
127 :param user_group: UserGroupID, user_group_name, or UserGroup instance
127 """
128 """
128 return self._get_instance(
129 return self._get_instance(
129 db.UserGroup, user_group, callback=db.UserGroup.get_by_group_name)
130 db.UserGroup, user_group, callback=db.UserGroup.get_by_group_name)
130
131
131 def _get_repo(self, repository):
132 def _get_repo(self, repository):
132 """
133 """
133 Helper method to get repository by ID, or repository name
134 Helper method to get repository by ID, or repository name
134
135
135 :param repository: RepoID, repository name or Repository Instance
136 :param repository: RepoID, repository name or Repository Instance
136 """
137 """
137 return self._get_instance(
138 return self._get_instance(
138 db.Repository, repository, callback=db.Repository.get_by_repo_name)
139 db.Repository, repository, callback=db.Repository.get_by_repo_name)
139
140
140 def _get_perm(self, permission):
141 def _get_perm(self, permission):
141 """
142 """
142 Helper method to get permission by ID, or permission name
143 Helper method to get permission by ID, or permission name
143
144
144 :param permission: PermissionID, permission_name or Permission instance
145 :param permission: PermissionID, permission_name or Permission instance
145 """
146 """
146 return self._get_instance(
147 return self._get_instance(
147 db.Permission, permission, callback=db.Permission.get_by_key)
148 db.Permission, permission, callback=db.Permission.get_by_key)
148
149
149 @classmethod
150 @classmethod
150 def get_all(cls):
151 def get_all(cls):
151 """
152 """
152 Returns all instances of what is defined in `cls` class variable
153 Returns all instances of what is defined in `cls` class variable
153 """
154 """
154 return cls.cls.getAll()
155 return cls.cls.getAll()
General Comments 0
You need to be logged in to leave comments. Login now