##// END OF EJS Templates
Fix zope profile extension....
Kiorky -
Show More
@@ -1,321 +1,324 b''
1 1 # -*- coding: utf-8 -*-
2 2 """ An ipython profile for zope and plone.
3 3
4 4 Some ideas stolen from http://www.tomster.org.
5 5
6 6
7 7 Authors
8 8 -------
9 9 - Stefan Eletzhofer <stefan.eletzhofer@inquant.de>
10 10 """
11 11
12 12 # File: ipy_profile_zope.py
13 13 #
14 14 # Copyright (c) InQuant GmbH
15 15 #
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19
20 20 from IPython.core import ipapi
21 21 from IPython.core import release
22 22 from types import StringType
23 23 import sys
24 24 import os
25 25 import textwrap
26 26
27 sys_oldstdin = sys.stdin
28
27 29 # The import below effectively obsoletes your old-style ipythonrc[.ini],
28 30 # so consider yourself warned!
29 31 # import ipy_defaults
30 32
31 33 _marker = []
32 34 def shasattr(obj, attr, acquire=False):
33 35 """ See Archetypes/utils.py
34 36 """
35 37 if not acquire:
36 38 obj = obj.aq_base
37 39 return getattr(obj, attr, _marker) is not _marker
38 40
39 41 class ZopeDebug(object):
40 42 def __init__(self):
41 43
42 44 self.instancehome = os.environ.get( "INSTANCE_HOME" )
43 45
44 46 configfile = os.environ.get( "CONFIG_FILE" )
45 47 if configfile is None and self.instancehome is not None:
46 48 configfile = os.path.join( self.instancehome, "etc", "zope.conf" )
47 49
48 50 if configfile is None:
49 51 raise RuntimeError( "CONFIG_FILE env not set" )
50 52
51 53 print "CONFIG_FILE=", configfile
52 54 print "INSTANCE_HOME=", self.instancehome
53 55
54 56 self.configfile = configfile
55 57
56 58 try:
57 59 from Zope2 import configure
58 60 except ImportError:
59 61 from Zope import configure
60 62
61 63 configure( configfile )
62 64
63 65 try:
64 66 import Zope2
65 67 app = Zope2.app()
66 68 except ImportError:
67 69 import Zope
68 70 app = Zope.app()
69 71
70 72 from Testing.makerequest import makerequest
71 73 self.app = makerequest( app )
72 74
73 75 try:
74 76 self._make_permissive()
75 77 print "Permissive security installed"
76 78 except:
77 79 print "Permissive security NOT installed"
78 80
79 81 self._pwd = self.portal or self.app
80 82
81 83 try:
82 84 from zope.component import getSiteManager
83 85 from zope.component import getGlobalSiteManager
84 86 from zope.app.component.hooks import setSite
85 87
86 88 if self.portal is not None:
87 89 setSite( self.portal )
88 90
89 91 gsm = getGlobalSiteManager()
90 92 sm = getSiteManager()
91 93
92 94 if sm is gsm:
93 95 print "ERROR SETTING SITE!"
94 96 except:
95 97 pass
96 98
97 99
98 100 @property
99 101 def utils(self):
100 102 class Utils(object):
101 103 commit = self.commit
102 104 sync = self.sync
103 105 objectInfo = self.objectInfo
104 106 ls = self.ls
105 107 pwd = self.pwd
106 108 cd = self.cd
107 109 su = self.su
108 110 getCatalogInfo = self.getCatalogInfo
109 111
110 112 @property
111 113 def cwd(self):
112 114 return self.pwd()
113 115
114 116 return Utils()
115 117
116 118 @property
117 119 def namespace(self):
118 120 return dict( utils=self.utils, app=self.app, portal=self.portal )
119 121
120 122 @property
121 123 def portal(self):
122 124 portals = self.app.objectValues( "Plone Site" )
123 125 if len(portals):
124 126 return portals[0]
125 127 else:
126 128 raise KeyError( "No Plone Site found.")
127 129
128 130 def pwd(self):
129 131 return self._pwd
130 132
131 133 def _make_permissive(self):
132 134 """
133 135 Make a permissive security manager with all rights. Hell,
134 136 we're developers, aren't we? Security is for whimps. :)
135 137 """
136 138 from Products.CMFCore.tests.base.security import PermissiveSecurityPolicy
137 139 import AccessControl
138 140 from AccessControl.SecurityManagement import newSecurityManager
139 141 from AccessControl.SecurityManager import setSecurityPolicy
140 142
141 143 _policy = PermissiveSecurityPolicy()
142 144 self.oldpolicy = setSecurityPolicy(_policy)
143 145 newSecurityManager(None, AccessControl.User.system)
144 146
145 147 def su(self, username):
146 148 """ Change to named user.
147 149 """
148 150 # TODO Make it easy to change back to permissive security.
149 151 user = self.portal.acl_users.getUser(username)
150 152 if not user:
151 153 print "Can't find %s in %s" % (username, self.portal.acl_users)
152 154 return
153 155
154 156 from AccessControl import ZopeSecurityPolicy
155 157 import AccessControl
156 158 from AccessControl.SecurityManagement import newSecurityManager, getSecurityManager
157 159 from AccessControl.SecurityManager import setSecurityPolicy
158 160
159 161 _policy = ZopeSecurityPolicy
160 162 self.oldpolicy = setSecurityPolicy(_policy)
161 163 wrapped_user = user.__of__(self.portal.acl_users)
162 164 newSecurityManager(None, user)
163 165 print 'User changed.'
164 166 return getSecurityManager().getUser()
165 167
166 168 def getCatalogInfo(self, obj=None, catalog='portal_catalog', query=None, sort_on='created', sort_order='reverse' ):
167 169 """ Inspect portal_catalog. Pass an object or object id for a
168 170 default query on that object, or pass an explicit query.
169 171 """
170 172 if obj and query:
171 173 print "Ignoring %s, using query." % obj
172 174
173 175 catalog = self.portal.get(catalog)
174 176 if not catalog:
175 177 return 'No catalog'
176 178
177 179 indexes = catalog._catalog.indexes
178 180 if not query:
179 181 if type(obj) is StringType:
180 182 cwd = self.pwd()
181 183 obj = cwd.unrestrictedTraverse( obj )
182 184 # If the default in the signature is mutable, its value will
183 185 # persist across invocations.
184 186 query = {}
185 187 if indexes.get('path'):
186 188 from string import join
187 189 path = join(obj.getPhysicalPath(), '/')
188 190 query.update({'path': path})
189 191 if indexes.get('getID'):
190 192 query.update({'getID': obj.id, })
191 193 if indexes.get('UID') and shasattr(obj, 'UID'):
192 194 query.update({'UID': obj.UID(), })
193 195 if indexes.get(sort_on):
194 196 query.update({'sort_on': sort_on, 'sort_order': sort_order})
195 197 if not query:
196 198 return 'Empty query'
197 199 results = catalog(**query)
198 200
199 201 result_info = []
200 202 for r in results:
201 203 rid = r.getRID()
202 204 if rid:
203 205 result_info.append(
204 206 {'path': catalog.getpath(rid),
205 207 'metadata': catalog.getMetadataForRID(rid),
206 208 'indexes': catalog.getIndexDataForRID(rid), }
207 209 )
208 210 else:
209 211 result_info.append({'missing': rid})
210 212
211 213 if len(result_info) == 1:
212 214 return result_info[0]
213 215 return result_info
214 216
215 217 def commit(self):
216 218 """
217 219 Commit the transaction.
218 220 """
219 221 try:
220 222 import transaction
221 223 transaction.get().commit()
222 224 except ImportError:
223 225 get_transaction().commit()
224 226
225 227 def sync(self):
226 228 """
227 229 Sync the app's view of the zodb.
228 230 """
229 231 self.app._p_jar.sync()
230 232
231 233 def objectInfo( self, o ):
232 234 """
233 235 Return a descriptive string of an object
234 236 """
235 237 Title = ""
236 238 t = getattr( o, 'Title', None )
237 239 if t:
238 240 Title = t()
239 241 return {'id': o.getId(),
240 242 'Title': Title,
241 243 'portal_type': getattr( o, 'portal_type', o.meta_type),
242 244 'folderish': o.isPrincipiaFolderish
243 245 }
244 246
245 247 def cd( self, path ):
246 248 """
247 249 Change current dir to a specific folder.
248 250
249 251 cd( ".." )
250 252 cd( "/plone/Members/admin" )
251 253 cd( portal.Members.admin )
252 254 etc.
253 255 """
254 256 if type(path) is not StringType:
255 257 path = '/'.join(path.getPhysicalPath())
256 258 cwd = self.pwd()
257 259 x = cwd.unrestrictedTraverse( path )
258 260 if x is None:
259 261 raise KeyError( "Can't cd to %s" % path )
260 262
261 263 print "%s -> %s" % ( self.pwd().getId(), x.getId() )
262 264 self._pwd = x
263 265
264 266 def ls( self, x=None ):
265 267 """
266 268 List object(s)
267 269 """
268 270 if type(x) is StringType:
269 271 cwd = self.pwd()
270 272 x = cwd.unrestrictedTraverse( x )
271 273 if x is None:
272 274 x = self.pwd()
273 275 if x.isPrincipiaFolderish:
274 276 return [self.objectInfo(o) for id, o in x.objectItems()]
275 277 else:
276 278 return self.objectInfo( x )
277 279
278 280 zope_debug = None
279 281
280 282 def ipy_set_trace():
281 283 from IPython.core import debugger
282 284 debugger.Pdb().set_trace()
283 285
284 286 def main():
285 287 global zope_debug
286 288 ip = ipapi.get()
287 289 o = ip.options
288 290 # autocall to "full" mode (smart mode is default, I like full mode)
289 291
290 292 SOFTWARE_HOME = os.environ.get( "SOFTWARE_HOME" )
291 293 sys.path.append( SOFTWARE_HOME )
292 294 print "SOFTWARE_HOME=%s\n" % SOFTWARE_HOME
293 295
294 296 zope_debug = ZopeDebug()
295 297
296 298 # <HACK ALERT>
297 299 import pdb;
298 300 pdb.set_trace = ipy_set_trace
299 301 # </HACK ALERT>
300 302
301 303 # I like my banner minimal.
302 304 o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0],release.version)
303 305
304 306 print textwrap.dedent("""\
305 307 ZOPE mode iPython shell.
306 308
307 309 Bound names:
308 310 app
309 311 portal
310 312 utils.{ %s }
311 313
312 314 Uses the $SOFTWARE_HOME and $CONFIG_FILE environment
313 315 variables.
314 316 """ % ( ",".join([ x for x in dir(zope_debug.utils) if not x.startswith("_") ] ) ) )
315 317
316 318
319 sys.stdin = sys_oldstdin
317 320 ip.user_ns.update( zope_debug.namespace )
318 321
319 322
320 323 main()
321 324 # vim: set ft=python ts=4 sw=4 expandtab :
General Comments 0
You need to be logged in to leave comments. Login now